【问题标题】:ios use object to return a function and use itios使用对象返回一个函数并使用它
【发布时间】:2011-09-13 21:03:39
【问题描述】:

我有一个很大的疑问: 我在这样的类中有我的功能:

-(Shot*) getShot:(int)shot {
    NSString *sqlStr = [NSString stringWithFormat:@"SELECT * FROM tbShots where nShot = %d ", shot];
    NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString *documentFolderPath = [searchPaths objectAtIndex:0];
    NSString *dbFilePath = [documentFolderPath stringByAppendingPathComponent:DATABASE_NAME_EXT];

    if (dbFilePath == NULL) {
        NSLog(@"dbFilePath is NULL");
    }

    sqlite3 *dbHandle;
    if (sqlite3_open([dbFilePath UTF8String], &dbHandle)) {
        NSLog(@"sqlite3_open: failed");
    }

    sqlite3_stmt *preparedStatement;
    const char* queryStatement = [sqlStr UTF8String];
    sqlite3_prepare_v2(dbHandle, queryStatement, -1, &preparedStatement, NULL);

    Shot *s = nil;
    NSString * note = @"";
    while( sqlite3_step(preparedStatement) == SQLITE_ROW)
    {
        s = [[Shot alloc] initWithShot:shot];
    }

    sqlite3_finalize(preparedStatement);
    sqlite3_close(dbHandle);    
    return s;
}

在这个类之外我使用这个:

  Shot* sP = [appDelegate getShot:nTarget];
  [self drawShoot:sP];

但我认为这不是检索对象实例并使用它的正确方法... 最好的方法是什么??? 也是在使用了实例sP之后,我需要释放吗?如果我释放操作也会影响 appDelegate 类?

谢谢

【问题讨论】:

    标签: objective-c ios object release instance


    【解决方案1】:

    s = [[镜头分配] initWithShot:shot]; 使其自动释放对象 [[[Shot alloc] initWithShot:shot] autorelease];然后你的方法返回自动释放的对象。 射击* sP = [appDelegate getShot:nTarget]; [自己的drawShoot:sP]; 那应该没问题。否则,当您返回 s 时,Shot 对象“s”上的保留计数为 1;在你的方法中。

    【讨论】:

    • 感谢 chang,所以如果我将 Shot* 的创建更改为 autorelase 是解决方案...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-14
    • 2013-08-20
    • 1970-01-01
    相关资源
    最近更新 更多