【问题标题】:Newbie IPhone developer using Instruments panel: Where is my leak?使用 Instruments 面板的新手 iPhone 开发人员:我的漏洞在哪里?
【发布时间】:2011-04-11 08:56:27
【问题描述】:

更新


我已经更新了 planets.m/h 文件以反映评论者提出的建议(感谢 bbum 和 DarkDust。 我的工厂方法现在都调用 autorelease,如下所示:

- (Planet *) initWithName: (NSString *)name;
+ (Planet *) planetWithNameAndMoons:(NSString *)name moons:(id)firstObj, ... NS_REQUIRES_NIL_TERMINATION;
+ (Planet *) planetWithName:(NSString *)name;
+ (Planet *) planetWithResultSet:(FMResultSet *)resultSet;

现在我的 init 看起来像这样

- (id)init {
    self = [super init];
    self.Id = 0;
    self.SupportsLife = NO;
    self.Moons =  [NSMutableArray array];   
    return self;
}

我在我的第二个控制器中调用planetWithName 离开根。我就是这样用的

- (Planet *)newPlanet
{
    int i = 0;
    Planet *planet = nil;
    NSMutableDictionary *criteria = [NSMutableDictionary new];

    do {
        i += 1;
        [criteria setValue: [NSString stringWithFormat:@"Planet %d", i] forKey: @"Name"];
        planet = [[PlanetRepo SharedRepo] Find: criteria];
    } while (planet != nil);    // if a planet is found with that name, keep looking...

    planet = [Planet planetWithName: (NSString *)[criteria valueForKey:@"Name"]];
    [planet retain];

    [criteria release];
    criteria = nil;

    return planet;
}

这是我的 PlanetRepo 类(注意,它是围绕 FMDB 进行的) PlanetRepo.h

#import <Foundation/Foundation.h>
#import "Planet.h"

@interface PlanetRepo : NSObject { 
    FMDatabase * _repoSource;
}

+ (PlanetRepo *) SharedRepo;

- (Planet *)Find:(NSDictionary *)criteria;
- (NSMutableArray *)GetAll;
- (Planet *)GetById:(id ) Id;
- (BOOL) Save:(Planet *) planet;
- (BOOL) Delete: (Planet *) planet;

- (BOOL) Open:(NSString *)repoSource;
- (void) Close;

@end

@interface PlanetRepo (Private)
- (NSError *) CreateDatabaseIfNeeded:(NSString *)databasePath;
@end

行星.m

#import "FMDatabase.h"
#import "PlanetRepo.h"
#import "Planet.h"

@implementation PlanetRepo

+ (PlanetRepo *)SharedRepo 
{   
    static PlanetRepo *_sharedRepo;
    @synchronized(self) 
    {
        if (!_sharedRepo) 
            _sharedRepo = [[super alloc] init]; 
    }
    return _sharedRepo;
}

+ (id) alloc { 
    return [self SharedRepo]; 
}

- (BOOL) Open: (NSString *)repoSource 
{   
    NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *databasePath = [documentsDirectory stringByAppendingPathComponent: repoSource];
    NSError *error = [self CreateDatabaseIfNeeded: databasePath];

    BOOL result = (error == nil);
    if(result) 
    {
        _repoSource = (FMDatabase *)[FMDatabase databaseWithPath:databasePath];
        [_repoSource retain];
        result = [_repoSource open];
        if (result) 
            NSLog(@"Planet Repo open successful!");
        else 
        {
            NSLog(@"Could not open Planet Repo.");
            [self Close];
        }
    }       
    else 
        NSLog(@"Could not copy db.", [error localizedDescription]);
    return result;
}

- (void) Close 
{
    [_repoSource release];
    _repoSource = nil;
}

- (void) dealloc 
{
    [self Close];
    [super dealloc];
}

- (Planet *)Find:(NSDictionary *)criteria
{
    if (criteria == nil) return nil;

    const NSUInteger criteriaCount = [criteria count];
    if (criteriaCount == 0) return nil;

    NSMutableString *temp = [NSMutableString stringWithString: @"SELECT Id, Name, SupportsLife FROM planet WHERE"];
    NSMutableArray *values = [[NSMutableArray alloc] initWithCapacity:criteriaCount];
    int i = 0;
    for (id key in criteria) 
    {
        [values addObject: [criteria objectForKey:key]];
        NSLog(@"key: %@, value: %@", key, [values objectAtIndex:i] );

        [temp appendString: [NSString stringWithFormat:@" %@=?", key ] ];
        if ( i < (criteriaCount - 1) ) 
            [temp appendString: @","];
        i++;
    }

    NSString *sql = [NSString stringWithString:temp];
    NSLog(@"sql: [%@]", sql);
    FMResultSet *resultSet = [_repoSource executeQuery:sql withArgumentsInArray: values ];

    Planet *planet = nil;
    if ( [resultSet hasAnotherRow] )
        planet = [Planet planetWithResultSet: resultSet];

    [values release];
    [resultSet close];

    return planet;
}

-(NSMutableArray *)GetAll
{
    NSMutableArray* resultsArray = [[NSMutableArray new] autorelease];
    FMResultSet *resultSet = [_repoSource executeQuery:@"SELECT Id, Name, SupportsLife FROM planet ORDER BY Name ASC"];
    while ([resultSet next]) 
        [resultsArray addObject:  [Planet planetWithResultSet:resultSet] ];
    [resultSet close];

    return resultsArray;
}

- (Planet *) GetById:(id) Id
{
    if( ![_repoSource open]) return NULL;

    Planet *planet = NULL;
    FMResultSet *resultSet = [_repoSource executeQuery:@"SELECT Id, Name, SupportsLife FROM planet WHERE Id=?" withArgumentsInArray:Id];
    if ([resultSet next])
        planet = [Planet planetWithResultSet:resultSet];
    [resultSet close];

    return planet;
}

- (BOOL) Save:(Planet *) planet
{
    if( ![_repoSource open]) return NO;

    [_repoSource beginTransaction];
    BOOL result = NO;
    if (planet.Id == 0) 
    {
        result = [_repoSource executeUpdate: @"INSERT INTO \"planet\" (Name,SupportsLife) values (?,?);", planet.Name, planet.SupportsLife];
        planet.Id = [_repoSource lastInsertRowId];
    }
    else 
        result = [_repoSource executeUpdate: @"UPDATE \"planet\" SET Name=?, SupportsLife=? WHERE Id=?", 
                  planet.Name, 
                  [NSNumber numberWithBool:planet.SupportsLife], 
                  [NSNumber numberWithInt:planet.Id]];


    if (result == YES)
        [_repoSource commit];
    else {
        [_repoSource rollback];
        NSLog( @"%@", [_repoSource lastErrorMessage] );
    }
    return result;  
}

- (BOOL) Delete: (Planet *) planet
{
    if( ![_repoSource open]) return NO;

    [_repoSource beginTransaction];
    BOOL result = [_repoSource executeUpdate: @"DELETE FROM \"planet\" WHERE Id=?", [NSNumber numberWithInt:planet.Id]];

    if (result == YES)
        [_repoSource commit];
    else {
        [_repoSource rollback];
        NSLog( @"%@", [_repoSource lastErrorMessage] );
    }
    return result;  
}

- (NSError *) CreateDatabaseIfNeeded:(NSString *)databasePath 
{   
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL doesDBExist = [fileManager fileExistsAtPath: databasePath];

    if (doesDBExist == NO )
    {
        NSString* dbFileName = [databasePath lastPathComponent];

        //the database does not exist, so we will copy it to the users document directory...
        NSString *sourceDbPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:dbFileName];

        NSError *error;
        if (![fileManager copyItemAtPath:sourceDbPath toPath:databasePath error:&error]) 
        {
            NSLog(@"Could not copy db.", [error localizedDescription]);
            return [error autorelease];
        }
    }
    return nil;
}

@end

原创


我最近一直在研究目标 c。它是一种很好的语言,但作为一个 .Net 人,这种内存管理的东西让我很生气! :)

我有一个名为 Planet 的示例类,当我通过仪表板运行时,我得到以下信息:

http://i.stack.imgur.com/QYdxB.jpg(图片)

Leaked Object |  Address  |   Size   | Responsible Library | Responsible Frame
--------------+-----------+----------+---------------------+-------------------
   Planet     | 0x7136380 | 32 Bytes | NavTest             | +[Planet newWithName:]
   Planet     | 0x712da20 | 32 Bytes | NavTest             | -[Planet init]
   Planet     | 0x5917a20 | 32 Bytes | Foundation          | -[NSPlaceholderString

我认为这意味着我在 [Planet init] 中创建数组时遇到了问题?

我也在这里列出了我的类文件。非常感谢您对此提供任何帮助。

行星.h

#import <Foundation/Foundation.h>
#import "FMDatabase.h"

@class Planet;

@interface Planet : NSObject { }

@property (nonatomic, assign) int Id;
@property (nonatomic, copy) NSString *Name;
@property (nonatomic, retain) NSMutableArray *Moons;
@property (nonatomic, assign) BOOL SupportsLife;

- (Planet *)initWithName: (NSString *)name;

+ (Planet *) newWithNameAndMoons:(NSString *)name moons:(id)firstObj, ... NS_REQUIRES_NIL_TERMINATION;
+ (Planet *) newWithName:(NSString *)name;
+ (Planet *) readPlanetFrom:(FMResultSet *)resultSet;

@end

行星.m

#import "Planet.h"
#import "FMDatabase.h"

@implementation Planet

@synthesize Id;
@synthesize Name; 
@synthesize Moons; 
@synthesize SupportsLife; 

- (NSString *) description {
 return [NSString stringWithFormat:@"ID: %d\nName: %@", Id ,Name];
}

- (void) dealloc {
 [Moons release];
 [Name release];

 Moons = nil;
 Name = nil;
 [super dealloc];
}

- (id)initWithName:(NSString *)aName {
 self = [self init];
 if (self) self.Name = aName;
 return self;
}

- (id)init {
 self = [super init];
 self.Id = 0;
 self.SupportsLife = NO;
 NSMutableArray *tmp = [NSMutableArray new]; 
 self.Moons = tmp;
 [tmp release];
 tmp = nil;
 return self;
}

+ (Planet *) newWithName:(NSString *)name {
 return [[self alloc] initWithName: name];
}

+ (Planet *)newWithNameAndMoons:(NSString *)name moons:(id)firstObj, ...   {
 Planet *planet = [self newWithName: name];

 va_list args;
    va_start(args, firstObj);
    for (id arg = firstObj; arg != nil; arg = va_arg(args, id))
 {
        [planet.Moons addObject: arg];
  [arg release];
 }
    va_end(args);
 return planet;
}

+ (Planet *) readPlanetFrom:(FMResultSet *)resultSet
{
 Planet *planet = [[self alloc] init]; 
 planet.Id = [resultSet intForColumn:@"Id"];
 planet.Name = [resultSet stringForColumn:@"Name"];
 planet.SupportsLife = [resultSet boolForColumn: @"SupportsLife"];
 return [planet autorelease];
}
@end

【问题讨论】:

  • 仪器没有告诉你你的 init 和 newWithName 有问题。它告诉你这是创建泄漏对象的地方。您可以展开负责的框架以查看创建对象时的整个堆栈,这可能有助于您找出稍后没有正确释放它的原因。
  • 感谢所有评论的人。我接受了 DarkDust 和 bbum 的建议,并将我的工厂方法重命名为以行星开始。我知道这是一个 obj-c 风格的问题,但我很高兴知道什么是正确使用。此外,我将 Moons 创建更改为调用 self.Moons = [NSMutableArray array];

标签: iphone objective-c memory-management memory-leaks instruments


【解决方案1】:

一些问题:

  • 实例变量和属性应以小写字母开头(以消除类名的歧义)

  • 在您的 init 方法中分配 tmp = nil; 没有必要——但没有害处——(顺便说一句,这需要 if(self) {...} 测试)。

  • 你可以通过说self.moons = [NSMutableArray array];来避免使用tmp变量

这是一个可能的泄漏源是以下方法:

+ (Planet *) newWithName:(NSString *)name {
 return [[self alloc] initWithName: name];
}

确实应该是这样的:

+ (id) planetWithName: (NSString *) aName {
    return [[[self alloc] initWithName: name] autorelease];
}

还有,这个:

+ (Planet *) readPlanetFrom:(FMResultSet *)resultSet

应该是这样的:

+ (id) planetWithResultSet: (FMResultSet *) aResultSet

如果没有看到更多代码,很难确切地说出泄漏的来源。在启用保留/释放跟踪的情况下运行分配工具下的代码。选择一个泄漏的行星并查看所有保留/释放事件。会有额外的保留。

【讨论】:

  • 您能解释一下为什么您认为泄漏是+[Planet newWithName] 吗?它完全按照它应该做的事情,返回一个保留计数为 1 的实例。还是我错过了什么?不过,您绝对正确,+[Planet planetWithName:] with autorelease 是更好的风格。
  • 如果没有更多代码,很难得出结论,但我想调用者会执行类似 self.myPlanet = [Planet newWithName: @"Bob"] 的操作,其中 myPlanet 是声明为 retain@property
【解决方案2】:

尽我所能,我在这里找不到问题。我只有一个非常疯狂的猜测:你有一个单独的线程来分配这个星球吗?例如。通过performSelectorInBackground:?如果是这样,您首先需要设置一个 NSAutoreleasePool 并在方法结束时将其排空。如果这确实是问题所在,您会看到类似 *** _NSAutoreleaseNoPool(): Object 0x1234560 of class Foo autoreleased with no pool in place - just leaking

的消息

不过,我有一个评论:您对new 的使用并不常见。 newsynonym for [[SomeClass alloc] init]。但是,它的用法是very uncommon in Objective-C, almost deprecated

所以不是

tmp = [NSMutableArray new];
self.Moons = tmp;
[tmp release];

比较常见的写法:

self.Moons = [[[NSMutableArray alloc] init] autorelease];

或者更好:

self.Moons = [NSMutableArray array];

【讨论】:

  • 我没有直接调用 performSelectorInBackground:。框架是否会在某个时候自动执行此操作?我的目标是 ios 4。
  • 不,线程只是由你显式创建的(在内部,像 NSURLConnection 这样的一些类确实创建了自己的线程,但你永远不会注意到)。
猜你喜欢
  • 2020-01-19
  • 2014-03-19
  • 1970-01-01
  • 2013-12-22
  • 2014-07-23
  • 1970-01-01
  • 2011-07-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多