Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
207 views
in Technique[技术] by (71.8m points)

iphone - Memory Management in Objective-C

I wanna ask if I allocated an instance variable for private use in that class, should i release it immediately on site, or i can depend on dealloc function. (because maybe i will need it on other function) ?

//Player.h
@interface Player : NSObject
{
    NSMutableArray * objectArray;
}

- (void)awake;
- (void)add;

@end

//Player.m
@implementation Player : NSObject
{
    -(id) init {
        self = [super init];
        if (self !=  nil ){
            [self awake];
            [self add];
        }
        return self;
    }
    - (void) awake {
        objectArray = [[NSMutableArray alloc] init]; //is it cause leakage?
        [objectArray addObject:@"foobar"];
    }
    - (void) add {
        [objectArray addObject:@"foobar2"];
    }
    - (void) dealloc {
        [objectArray release];
        [super dealloc];
    }
}

@end

or should i using property to set the objectArray iVar?

//Player.h
@interface Player : NSObject
{
    NSMutableArray * objectArray;
}

@property (nonatomic,retain)NSMutableArray* objectArray;

- (void)awake;
- (void)add;

@end

//Player.m
@implementation Player : NSObject
{
    -(id) init {
        self = [super init];
        if (self !=  nil ){
            [self awake];
            [self add];
        }
        return self;
    }
    - (void) awake {
        self.objectArray = [[NSMutableArray alloc] init autorelease]; //cause leakage?
        [objectArray addObject:@"foobar"];
    }
    - (void) add {
        [objectArray addObject:@"foobar2"];
    }
    - (void) dealloc {
        [objectArray release];
        [super dealloc];
    }
}

@end

if both of them doesn't cause a leakage, what type should i use? should i always set iVar property, and access iVar value with self even if i only want to use it in this class?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I like to take the stance that if the instance variable should not be visible outside of the class then it should not be implemented as a property. But it's a personal thing that other developers may not agree with.

Either way you would need to release the objectArray in your classes dealloc method - which is what you're currently doing.

However you need to be careful with your awake method - if it's invoked multiple times then objectArray is leaked. This is the downside of not using properties. A use of self.objectArray = [[NSMutableArray alloc] init] here would have released the previous object.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...