Reputation: 183
I have 1 NSString *abc = @"Hardik"; i have NSMutableArray *array; now i had written [array addobject:abc];
then i'm printing,NSLog(@"array = %@", array);
but i'm getting NULL why? I have declared NSMutableArray *array; in a.h file i had set @property(nonatomic,retain)NSMutableArray *array; @synthesize array;
and i have synthesize it but getting value NULL I'm not able to understand it?
Upvotes: 0
Views: 130
Reputation: 64428
To trigger the synthesized accessor within a class itself, you must use self
. If you don't, you access the attribute's address directly bypassing the accessor methods. You need:
NSString *abc = @"Hardik";
[self.array addobject:abc];
NSLog(@"array = %@", self.array);
The reason this is important is that the synthesized methods usually also initialize the property. The internals of the synthesize array method would look something like:
-(NSArray *) array{
if (array!=nil) {
return array;
}
array=[[NSMutableArray alloc] initWithCapacity:1];
return array;
}
self.propertyName
is really just shorthand for [self propertyName]
and self.propertyName=someValue
is just shorthand for [self setPropertyName:someValue]
.
Until you call self.array
at least once, the array property is not initialized.
However, just to confuse things, once you have called self.array
once it is initialized so you can just call array
directly. So...
[self.array addObject:abc];
NSLog(@"array = %@", array);
...works while the converse would return just an empty array.
So the rules are:
propertyName
gives you the address
of the property but does not call
the getter/setter accessor methods. self.propertyName
calls the
getter/setter accessor methods but
does not access attribute directly. myClass.propertyName
calls the
getter/setter accessor methods.Upvotes: 0
Reputation: 13807
It sounds like your NSMutableArray* array property may not have been initialised?
Can you post your class init method?
Upvotes: 0
Reputation: 52565
You also need to initialise your array:
array = [[NSMutableArray alloc] initWithCapacity:10];
This is pretty fundamental stuff. Have you read the "Learning Objective C Primer" yet?
Upvotes: 4
Reputation: 26859
It sounds like you haven't actually allocated array
. Generally, you would do this in your initializer. (Don't forget to add a release
to your dealloc
method, too.) @synthesize
creates the getter and setter, but you still have to handle allocating/deallocating the object yourself.
Upvotes: 3