Iphone 保留要在其他方法中使用的NSString值

Iphone 保留要在其他方法中使用的NSString值,iphone,objective-c,cocoa-touch,Iphone,Objective C,Cocoa Touch,在.h中,我声明: // in database.h @interface database : UIViewController { NSString* databaseName; NSString* databasePath; } 在执行时,首先调用methodA,我获取指向我的database.db文件的databasePath: //methodA: in database.m - (void)methodA { databaseName = @"databas

在.h中,我声明:

// in database.h
@interface database : UIViewController {
    NSString* databaseName;
    NSString* databasePath;
}
在执行时,首先调用methodA,我获取指向我的database.db文件的databasePath:

//methodA: in database.m
- (void)methodA {
    databaseName = @"database.db";  
    NSArray* documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString* documentsDir = [documentsPath objectAtIndex:0];
    databasePath = [documentsDir stringByAppendingPathComponent:databaseName];

    NSFileManager* filemagar = [NSFileManager defaultManager];
    NSString* databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
    [filemagar copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];

    NSLog (@"databasePath is...%@", databasePath);

[filemagar release];
}
数据库路径将返回文件夹路径名“/Users/…”的字符串。这就是我需要的

接下来,当我调用方法B…:

//methodB: in database.m
- (void)methodB {
    NSLog (@"databasePath is now...%@", databasePath);
}
程序终止时,指向以前的方法字符串的数据库路径不再相同

如何保留数据库路径信息,以便以后在其他方法中使用

databasePath = [[documentsDir stringByAppendingPathComponent:databaseName] retain];
或者更好地了解属性。

这一行:

databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
应该是:

databasePath = [[documentsDir stringByAppendingPathComponent:databaseName] copy];
另一种方法是使用属性:

@interface database : UIViewController {
    NSString* databaseName;
    NSString* databasePath;
}

@property (nonatomic, copy) NSString *databaseName;
@property (nonatomic, copy) NSString* databasePath;
然后在您的
@实现中

@synthesize databaseName, databasePath;

- (void) dealloc {
   [self setDatabaseName:nil];
   [self setDatabasePath:nil];
   [super dealloc];
}

//rest of your implementation...

您可以通过两种方式执行此操作:

首先,您可以保留字符串:

databasePath = [[documentsDir stringByAppendingPathComponent:databaseName] retain];
Cocoa Touch使用引用计数进行内存管理,您可以了解它

其次,您可以创建属性。在.h文件中:

@property(nonatomic, copy) NSString *databasePath
设置时,请按如下方式使用:

[self setDatabasePath:stringByAppendingPathComponent:databaseName];

您可以阅读有关属性的内容。

问题在于您没有保留(或复制)字符串引用。其当前范围仅限于该方法的范围。一旦该方法退出,由于
stringByAppendingPathComponent:
方法返回的字符串的自动释放性质,对该字符串的引用将丢失

这里最简单的方法可能是将
databasePath
声明为
(非原子,复制)@property
。这样,当您将数据库路径的值指定给变量时,它会自动为您复制

@property(nonatomic, copy) NSString *databasePath;
然后更新代码以使用点语法

self.databasePath = ...;

不要忘记在您的
dealloc
方法中释放
databasePath。

databasePath
nil
,因为它被分配给
自动释放
对象,即
[documentsDir stringByAppendingPathComponent:databaseName]
。这就是为什么
databasePath
在方法之外不可用的原因

正如其他答案所给出的,您可以在
数据库路径
变量中
保留
它或
复制
它,以便它在
释放
之前一直可用