开发者

ios use object to return a function and use it

开发者 https://www.devze.com 2023-04-04 20:51 出处:网络
I have this big doubt: I have my function in a class like this: -(Shot*) getShot:(int)shot { NSString *sqlStr = [NSString stringWithFormat:@\"SELECT * FROM tbShots where nShot = %d \", shot];

I have this big doubt: I have my function in a class like this:

-(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;
}

and outside this class I use this:

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

but I think that is not the right method to retrieve an instance of an object and use it... what's the best way??? also after the use of the instance sP, I need to release? if I release the operation affect also the appDelegate class?

开发者_运维技巧

thanks


s = [[Shot alloc] initWithShot:shot]; make it autoreleased object to [[[Shot alloc] initWithShot:shot] autorelease]; and then your method returns autoreleased object. Shot* sP = [appDelegate getShot:nTarget]; [self drawShoot:sP]; should be fine then. otherwise you are left with retain count 1 on Shot object "s" when your return s; in your method.

0

精彩评论

暂无评论...
验证码 换一张
取 消