Autosynthesised property 'assets' will use synthesised


#1

In the examples given, instance variables such as NSString *label are included both within the curly brackets and as a @property.

But when I do the same thing in Employee.h with a NSMutableArray, i.e.

@interface Employee : Person { int employeeID; NSMutableArray *assets; } @property NSMutableArray *assets; @property int employeeID;

I can build the file, but receive a warning: Autosynthesised property ‘assets’ will use synthesised variable ‘_assets’ , not existing instance variable ‘assets’.

If I delete the @property line, everything works as expect. What’s going on here – why does is accept NSString repeated as a @property but not NSMutableArray?

What have I misunderstood?

Thanks


#2

[quote][code]@interface Employee : Person
{
int employeeID;
NSMutableArray *assets;
}
@property NSMutableArray *assets;
@property int employeeID;

@end
[/code][/quote]
That’s not quite right!

Declare it like this:

@interface Employee : Person
{
    int employeeID;
    NSMutableArray *_assets;
}
@property (copy) NSArray *assets;
@property int employeeID;
@end

You don’t want other objects to modify the assets directly, you want them to modify it through the interface provided by the Employee object.

Also if you are using the latest version of the Objective-C compiler, declare the interface like this:

// Employee.h

@interface Employee : Person

@property (copy) NSArray *assets;
@property int employeeID;

@end
// Employee.m
...
@implementation Employee 
{
    int employeeID;
    NSMutableArray *_assets;
}
...
@end

You can complement your understanding of properties by reading the section entitled Encapsulating Data in Programming with Objective-C. [See: developer.apple.com/library/mac … 10-CH5-SW1]


#3

Thank you for your reply – I appreciate it.

However, I’m still a little confused. I was trying to get the example in the book (first edition) to work. – and (copy) and _ are not mentioned at all yet, so I’m unclear what they’re supposed to do.

I think there are two things here:

  1. the book does not have a @property for assets – it merely declares it in the brackets. I’d added the property and forgotten to add the @synthesise. If either take out the property or add the @synthesis, the program builds with no error. Are you saying that the use of @property / @synthesize here is unwelcome because it means that the array is directly accessible by any other class/object?

  2. If I’ve understood you correctly, with the introduction of (copy) and _assets, you’re introducing something more advanced that has been covered in the book so far. I will certainly read the reference you pointed to – thanks very much.

Many thanks for your help.