Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

sam256

macrumors newbie
Original poster
Oct 4, 2011
4
0
If we initialize class property, created using
Code:
@property (nonatomic, retain) NSArray *prop
in the body of function
Code:
(void)init
in this way
Code:
prop = [NSArray arrayWithObjects:@"1", @"2", nil]
where will be a mistake in this code. What consequences in working program it will have and in what time moment, in what function will it happen?
 
If we initialize class property, created using
Code:
@property (nonatomic, retain) NSArray *prop
in the body of function
Code:
(void)init
in this way
Code:
prop = [NSArray arrayWithObjects:@"1", @"2", nil]
where will be a mistake in this code. What consequences in working program it will have and in what time moment, in what function will it happen?

It seems really clever to just write "prop", but after a few years of programming you will find it much better if a line of code clearly states what it does, like "self.prop" does. What's the variable behind that property called? It's not called "prop" as well, is it? In that case you are setting yourself up for trouble.
 
If we initialize class property, created using
Code:
@property (nonatomic, retain) NSArray *prop
in the body of function
Code:
(void)init
in this way
Code:
prop = [NSArray arrayWithObjects:@"1", @"2", nil]
where will be a mistake in this code. What consequences in working program it will have and in what time moment, in what function will it happen?

There's a couple of problems with code.

Firstly you're assigned an autoreleased object to an instance variable without retaining it. At some point the object whose address in prop will be released and then prop will point to a zombie. If you try to send a message to this object after it's begin released, your program is likely to crash. When? How knows. It might seems like your program is crashing randomly.

"But the property is retain!" I hear you say. Yes, but you're bypassing the property and assessing the instance variable directly.

You need to do one of the following (in ascending order of my preference).

Either:
Code:
prop = [[NSArray arrayWithObjects:@"1", @"2", nil] retain];
or:
Code:
prop = [[NSArray alloc] initWithObjects:@"1", @"2", nil];
or
Code:
self.prop = [NSArray arrayWithObjects:@"1", @"2", nil];
 
Dear gnasher729, jiminaus, thank you so much for your answers, they were very helpful!!!))
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.