简体   繁体   English

什么时候应该发布我的阵列?

[英]When should I release my array?

I am parsing some JSON from the internet and then adding them to an array which is the datasource for my UITableView. 我正在从互联网解析一些JSON,然后将它们添加到一个数组,这是我的UITableView的数据源。 I am not sure when I should be releasing my array? 我不确定何时应该发布我的阵列?

.h: items .h:物品

@property(nonatomic,retain)NSMutableArray*  items;

.m: connectionDidFinishLoading .m:connectionDidFinishLoading

// fetch succeeded    
    NSString* json_string = [[NSString alloc] initWithData:retrievedData encoding:NSUTF8StringEncoding];

    //Check ST status
    int status =  [[[[json_string objectFromJSONString] valueForKey:@"response"] valueForKey:@"status"]intValue];
    //NSLog(@"Status: %d", status);

    items = [[NSMutableArray alloc] init];
    NSDictionary* messages = [[NSDictionary alloc] init]; 

    switch (status) {
        case 200:
            messages = [[[json_string objectFromJSONString] valueForKey:@"messages"] valueForKey:@"message"];

            for (NSDictionary *message in messages)
            {
                [items addObject:message];
            }
            [self.tableView reloadData];
        break;

        default:
        break;
    }

One, you might want to declare items as an instance of NSMutableArray if you intend to call addObject: on it. 一,如果您打算在其上调用addObject:您可能希望将items声明为NSMutableArray的实例。

Two, declare it as a property so that if you end up getting it multiple times the older value will be released when you do. 二,将它声明为属性,这样如果你最终获得它多次,那么当你这样做时,旧的值将被释放。

self.items = [NSMutableArray array];

And the correct point of releasing it would be dealloc . 释放它的正确点是dealloc

Probably you don't want to release it immediately if you: 如果你:你可能不想立即释放它:

  • use didSelectRowAtIndexPath: method for detail views and pass this data to them 使用didSelectRowAtIndexPath:方法获取详细信息视图并将此数据传递给它们
  • define custom UITableViewCell styles in cellForRowAtIndexPath: method 在cellForRowAtIndexPath:方法中定义自定义UITableViewCell样式
  • use this data elsewhere 在别处使用这些数据

Best practice is declare an instance variable and synthesize it in .m, use in appropriate operations and release in dealloc method. 最佳实践是声明一个实例变量并在.m中合成它,在适当的操作中使用并在dealloc方法中释放。

One possible release point that you could use is where you refresh your data that shown on table. 您可以使用的一个可能的发布点是刷新表中显示的数据。

Example: 例:

I get dictionaries in an array from an API in my app and use something like that. 我从我的应用程序中的API获取数组中的字典并使用类似的东西。

MyTableViewController.h MyTableViewController.h

@interface MyTableViewController {
    NSMutableArray *items;
}

@property (nonatomic, retain) NSMutableArray *items;

@end

MyTableViewController.m MyTableViewController.m

@implementation MyTableViewController

@synthesize items;

- (void)dealloc
{
    [items release];
    [super dealloc];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [items count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *cellIdentifier = @"FilesCellIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier] autorelease];
    }

    cell.textLabel.text = [[items objectAtIndex:indexPath.row] valueForKey:@"name"];
    cell.imageView.image = [UIImage imageNamed:[[NSString alloc] initWithFormat:@"filetype_%@.png", [[items objectAtIndex:indexPath.row] valueForKey:@"type"]]];

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
        MyDetailViewController *detailViewController = [[MyDetailViewController alloc] initWithNibName:@"MyDetailViewController" bundle:[NSBundle mainBundle]];
        detailViewController.item = [items objectAtIndex:indexPath.row];
        [self.navigationController pushViewController:detailViewController animated:YES];
        [detailViewController release];
        detailViewController = nil;
    }
}

- (void)getItems
{
    [items release];
    items = [[NSMutableArray alloc] init];

    //Do some requests here

    for (NSDictionary *dict in results)
    {
        [items insertObject:dict atIndex:0];
    }

    [self.tableView reloadData];
    [self stopLoading];
}

@end

在错误的地方释放一段时间会导致内存泄漏,在分配之前你可能会遇到像if(){[... release]}这样的情况。没有经过测试但是这种释放可以避免泄漏。

The most common is to have the items variable as an attribute of your class, once you will probably need it to use in your tableView:cellForRowAtIndexPath: method. 最常见的是将items变量作为类的属性,一旦您可能需要在tableView:cellForRowAtIndexPath:方法中使用它。

So, having it as an attribute variable you can release it on the dealloc method. 因此,将它作为属性变量,您可以在dealloc方法上释放它。

It's clear that your array item will be used by UITableView to show data. 很明显, UITableView将使用您的数组item来显示数据。

First declare it as instance variable in your .h class. 首先在.h类中将其声明为实例变量。

.h class .h班

@interface MyClass 
{
  MSMutableArray* items;
}
@property(nonatomic,retain) MSMutableArray* items;

@end

In your .m class. 在你的.m课程中。

@synthesis iMyArray;

And you code for filling the array should be 而你填写数组的代码应该是

NSMutabelArray* itemsTemp = [[NSMutabelArray alloc] initWithCapacity:1];

messages = [[[json_string objectFromJSONString] valueForKey:@"messages"] valueForKey:@"message"];
[json_string release];

for (NSDictionary *message in messages) {
    NSLog(@"%@",[message valueForKey:@"body"]);
    [itemsTemp addObject:message];
}


self.items= itemsTemp;

[itemsTemp release];
itemsTemp = nil;

[self.tableView reloadData];

Now in dealloc release your array instance. 现在在dealloc释放你的数组实例。

-(void) dealloc
{
   if(items )
   {
    [items release];
    items = nil ;
   }
   [super dealloc];
}

Proper way is make it property in .h class, since you have declared it as property: remember one thing always alloc a property by using self. 正确的方法是在.h类中使它成为属性,因为你已经将它声明为属性:记住一件事总是通过使用self来分配属性。

your statement items=[[NSMutableArray alloc] init]; your statement items=[[NSMutableArray alloc] init];

is wrong.(use self) also since your property is retain type the using alloc on it increase retain count.that gives you a leak. 是错误的。(使用self)也因为你的属性是retain类型,使用它就会增加保留计数。这会给你一个泄漏。

so use in this way in viewDidLoad 所以在viewDidLoad以这种方式使用

NSMutableArray *tempArray=[[NSMutableArray alloc] init];
self.items=tempArray;
[tempArray release];

then release your items array in dealloc and set it nil in viewDidUnload 然后在dealloc释放你的items数组,并在viewDidUnload中将其设置为nil

- (void)viewDidUnload {
    [super viewDidUnload];
    self.items=nil;
}

- (void)dealloc {
    [self.items release];
[super dealloc];
}

Hope now you can understand how you should use this. 希望你现在可以理解你应该如何使用它。

According to Apple's documentation of UITableView reloadData method : 根据Apple的UITableView reloadData方法文档

"[...] For efficiency, the table view redisplays only those rows that are visible" “[...]为提高效率,表格视图仅重新显示那些可见的行”

That means yo should not release the items array as long as the table is being used, ie you have to declare the array as a property. 这意味着只要表正在使用,你就不应该释放items数组,即你必须将数组声明为属性。

First because if you scroll the view, you will still need the items information to display the rows below or above. 首先,因为如果滚动视图,您仍然需要items信息来显示下方或上方的行。

And second, because by being a property you ensure that a previous value is going to be released if you happen to assign a new value to items . 第二,因为作为一个属性可以确保先前的值会被释放,如果你碰巧分配一个新的价值items

Finally, the common place to release a property is in the dealloc method and depending on your implementation in viewDidUnload method. 最后,释放属性的常见位置是dealloc方法,具体取决于viewDidUnload方法中的实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 过渡到新的UIViewController时应何时发布? - When should I release the current UIViewController when transitioning to a new one? 我应该释放[NSMutableDictionary ValueForKey:]返回的数组吗 - Should I release array returned from [NSMutableDictionary ValueForKey: ] 我应该释放一个指向数组中项目的指针吗? - Should I release a pointer that's pointing to an item in an array? 我应该发布NSURL吗? - Should I release NSURL? 我什么时候应该释放[[UIApplication sharedApplication]委托]对象? - When should I release [[UIApplication sharedApplication] delegate] object? iPhone SDK:我应该如何/何时发布UITableView委托对象? - iPhone SDK: How/when should I release a UITableView delegate object? 我什么时候应该在 - (void)viewDidUnload而不是-dealloc中释放对象? - When should I release objects in -(void)viewDidUnload rather than in -dealloc? 我应该释放未使用的ivar吗? - Should I release an unused ivar? 为什么我应该在setter方法中将-autorelease发送给我的实例变量,而不是-release? - Why should I send -autorelease to my instance variable in my setter method, rather than -release? 如果以后会检测到触摸,应否发布添加到视图的UIImageView? - Should I release an UIImageView added to my view if I will detect touch on it later on?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM