1

I am creating my own custom object, and I am wondering if I need to retain my properties or use something else such as copy (which does what?)?

@interface Asset : NSObject {
    NSString *name;
    NSNumber *assetId;
    NSNumber *linkId;
    NSNumber *parentId;
}

@property (nonatomic, retain) NSString *name; // should I use retain here or something else?
@property (nonatomic, retain) NSNumber *assetId;
@property (nonatomic, retain) NSNumber *linkId;
@property (nonatomic, retain) NSNumber *parentId;

@end

Also, in my .m, do I also need synthesize as well as release?

3 Answers 3

4

The chapter on Declared Properties in The Objective-C Programming Language explains what copy does and about synthesizing accessors.

Sign up to request clarification or add additional context in comments.

Comments

1

My personal preference:

@interface Asset : NSObject {
    // no need to declare them here the @synthesize in the .m will sort all that out
}


// use copy for NSString as it is free for NSString instances and protects against NSMutableString instances being passed in...thanks to @bbum for this
@property (nonatomic, copy) NSString *name;

// no need for copy as NSNumber is immutable
@property (nonatomic,retain) NSNumber *assetId;
@property (nonatomic,retain) NSNumber linkId;
@property (nonatomic,retain) NSNumber parentId;

@end

3 Comments

You should use copy; it is free for NSString and defense against someone passing in a mutable string.
ah.. well that's something I've learnt today...is it also free on NSNumbers?
probably; copy is generally free on non-mutable objects (including things like NSArray).
1

For typical cases your .m will have lines like this:

@synthesize name;
...

That tells the compiler to automatically emit the getter/setter methods. You can also write/override these yourself. So, when someone does a fooAsset.name = x, your object will retain its own reference to 'x'. The other thing you need is a dealloc method to release the references to your members:

- (void)dealloc {
    [name release];
    ....
    [super dealloc];
}

Note that it'll still be appropriate if 'name' is never assigned; nil will silently eat the 'release' message.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.