容器类的内存管理

时间:2011-08-16 12:24:47

标签: iphone objective-c ios

我制作了一个容器类来存储一条推文。它通过传入一个字典对象来初始化,这是一条推文。

然后我存储了这些'推文'的数组,我处理这些推文以显示在表格中。

该项目现已完成,我正在审查目前的所有内容,我想知道将来有更好的方法可以做到这一点。内存处理是否正确。我使用'copy'声明了字符串成员变量,然后在dealloc中使用'release'而不是将它们设置为'nil'。

我的初学者是好还是可以改进?

Tweet.h     #import

@interface Tweet : NSObject 
{
NSString * _userName;
NSString * _tweetText;
NSString * _tweetURL;
}

@property (nonatomic, copy) NSString * userName;
@property (nonatomic, copy) NSString * tweetText;
@property (nonatomic, copy) NSString * tweetURL;

- (id) initWithDict:(NSDictionary *)productsDictionary; 

@end

Tweet.m     @implementation Tweet

@synthesize userName = _userName;
@synthesize tweetText = _tweetText;
@synthesize tweetURL = _tweetURL;

- (id) initWithDict:(NSDictionary *)productsDictionary 
{
NSDictionary *aDict = [productsDictionary objectForKey:@"user"];
self.userName = [aDict objectForKey:@"screen_name"];
self.tweetText = [productsDictionary objectForKey:@"text"];

NSRange match;
match = [self.tweetText rangeOfString: @"http://"];
if (match.location != NSNotFound)
{
    NSString *substring = [self.tweetText substringFromIndex:match.location];
    NSRange match2 = [substring rangeOfString: @" "];

    if (match2.location == NSNotFound)
    {
        self.tweetURL = substring;
    }
    else
    {
        self.tweetURL = [substring substringToIndex:match2.location];
    }
}
else 
{
    self.tweetURL = nil;
}

return self;
}

-(void) dealloc
{
[self.tweetText release];
[self.tweetURL release];
[self.userName release];
[super dealloc];
}

@end

非常感谢, 代码

1 个答案:

答案 0 :(得分:3)

乍一看,我发现这里没有固有的缺陷。看起来很好。我更愿意这样做:

-(void) dealloc
{
    [_tweetText release];
    [_tweetURL release];
    [_userName release];
    [super dealloc];
} 

但你所做的也很好。