NSArray initWithObjects:内存泄漏



这是我的代码:

    - (void)viewDidLoad{
[super viewDidLoad];
self.authorList = [[NSArray alloc] 
                   initWithObjects:@"Christie, Agatha", 
                   @"Archer, Jeffrey", nil];
self.title = @"Authors";

}

我在分配和初始化数组authorlist的第行遇到内存泄漏。我试着把autorelease放在authorlist上,但上面写着"Object send-autoreleases send too many times"。我还在学习记忆管理。

谢谢。

authorList的setter方法将保留数组,因此您需要在调用它后立即释放它:

NSArray *list = [[NSArray alloc] 
                initWithObjects:@"Christie, Agatha", 
                @"Archer, Jeffrey", nil];
self.authorList = list;
[list release];

或者你可以自动释放它:

self.authorList = [[[NSArray alloc] 
                   initWithObjects:@"Christie, Agatha", 
                   @"Archer, Jeffrey", nil] autorelease];

您在类中编写了dealloc方法吗?

如果您没有使用ARChttp://cocoa-touch.blogspot.ie/2008/09/memory-management-on-iphone.html

您不应该直接分配属性对象。

你应该这样分配:

 - (void)viewDidLoad{
      [super viewDidLoad];
       NSArray *tempArray = [[NSArray alloc] 
               initWithObjects:@"Christie, Agatha", 
               @"Archer, Jeffrey", nil];
       self.authorList = tempArray;
       [tempArray release];

      NSString *titleString = @"Authors";
      self.title = titleString;
      [titleString release];
 }

使用此

 self.authorList = [[[NSArray alloc] 
               initWithObjects:@"Christie, Agatha", 
               @"Archer, Jeffrey", nil] autorelease];

最新更新