开发者

Can I use one instance variable to point to different objects over its lifetime?

I have a simple question about using a pointer in Obj-C.

Is it bad practice to use one pointer for different instances of the same thing?

For example, if I have an UIViewController Class called Poster and I am using it in a UIViewController Class called MovieTheater

in MovieTheater.h:

@interface MovieTheater : UIViewController {
    Poster *newMoviePoster;

}

@property (nonatomic, retain) Poster *newMoviePoster;

- (void) changePoster:(NSString*)titleText;

Then in MovieTheater.m:

@synthesize newMoviePoster;


- (void)viewDidLoad
{
   [super viewDidLoad];
  newMoviePos开发者_如何转开发ter = [[Poster alloc]initWithTitle:@"COMING IN MAY"];



}

-(void) changePoster:(NSString*)titleText{

    newMoviePoster= [[Poster alloc]initWithTitle:titleText];

}


- (void)viewDidUnload
{
[newMoviePoster release];
}

Let's assume that we need to access the newMoviePoster object often, so releasing it before viewDidUnload breaks the app.

Is this legit code? It looks good to me, but I am relatively new in Obj-C.

Thanks!


Your code is wrong, it’s leaking memory. When you create a new object using the alloc call, you get a pointer to the allocated memory that you have to later release. You store this value to the newMoviePoster variable – so far so good. But when you call changePoster:, you overwrite the previous pointer with a new one. The old pointer to the allocated memory is gone and you will not be able to release the memory, it’s lost until your program quits.

This is easy to fix, but what really needs fixing is your understanding of Cocoa memory management. You could start by reading the Cocoa Memory Management Guide, that’s a must reading for any Cocoa programmer.

As for the original question, it’s fine to use one variable to point to several different objects over its lifetime. But it’s better to avoid it if possible, because it’s prone to bugs, as you have seen just now. This is one of the reasons why some programmers try to keep values from changing, see immutability and functional programming.


This is perfectly fine to do, except that you need to release the old instance of newMoviePoster before assigning the new one:

-(void) changePoster:(NSString*)titleText{
    [newMoviePoster release]
    newMoviePoster= [[Poster alloc]initWithTitle:titleText];
}

Or, use the synthesized setter:

self.newMoviePoster = [[[Poster alloc] initWithTitle:titleText] autorelease];


Pay attention when you keep pointers to an instance, it could cause some nightmare bugs if you're trying to use the pointer to an object that was autoreleased, or released by your own code and even worse : released automatically after a memoy warning.

Finding the error origin could be almost impossible.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜