ios - 内存保留问题

标签 ios

我正在编写一个带有导航器 Controller 和带有疫苗数组的基类的 iOS 应用程序。

@synthesize vaccines;

self.vaccines = [[NSMutableArray alloc] initWithObjects:nil];

Vaccine *v = [[Vaccine alloc] init];
[v setVaxName: [NSMutableString stringWithString: @"Anthrax" ]];
[v setAdultDescr: [NSMutableString stringWithString: @"" ]];
[v setPed06Descr: [NSMutableString stringWithString: @"" ]];
[v setPed718Descr: [NSMutableString stringWithString: @"" ]];
[v setPedCatchDescr: [NSMutableString stringWithString: @"" ]];
[self.vaccines addObject:v];
[v release];

我在委托(delegate)类中使用此方法来访问疫苗的名称:

- (NSString *) getVaccineName: (NSInteger) i
{
if ([vaccines count] > i)
{
    return [[vaccines objectAtIndex:i] getVaxName];
}
return @"";
}

我使用 Vaccine 类中的方法来访问该名称。

(NSMutableString *) getVaxName
{
    return vaxname;
}

创建后,疫苗完好无损并返回“炭疽”。但是,当我转到另一个页面时,我调用:

NSString *str = [delegate getVaccineName: 0];

这会返回垃圾。

我错过了什么?

最佳答案

您可以尝试使用 Vaccine 类,如下所示:

// Vaccine.h
@interface Vaccine: NSObject {
    NSString *vaxName;
    NSString *adultDescr;
    // crete the other instance variables
}
@property(copy, nonatomic) NSString *vaxName;
@property(copy, nonatomic) NSString *adultDescr;
// add the other accessor properties
@end

// Vaccine.m
@implementation Vaccine

@synthesize vaxName
@synthesize adultDescr
// synthesize the other properties

@end

此时,您可以修改您提供的第一个代码片段,如下所示:

Vaccine *v = [[Vaccine alloc] init];
v.vaxName = @"name"; // its the same as [v setVaxName:@"name"];
v.adultDescr = @"descr";
// set the other properties

NSString 不是像 int、float 等那样的原始类型。它是一个对象。如果您想将其保留在内存中,则必须增加其保留计数。简单地分配它,它不允许您将其保留在内存中。欲了解更多信息,请参阅:memory management

记住在 Vaccine 类的 dealloc 方法中释放内存:

- (void)dealloc
{
   self.vaxName = nil;
   self.adultDescr = nil;
   // release the other properties
}

根据夸张的建议,例如,最好在单例类中维护您的模型(您的疫苗数组)。还可以使用其他解决方案(即在 NSUserDefaults 中保存/恢复模型等)。通过这种方式,您可以在应用程序的任何部分访问它。

关于ios - 内存保留问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8567357/

相关文章:

objective-c - 需要类型转换

ios - 在应用程序终止后使用 NSNotification 处理 UIViewController 中的 UILocalNotification

ios - session 过期时如何移动登录页面

ios - 为什么在 SceneKit 着色器修改器中使用 glsl 或定义函数只会产生错误?

angular ui路由器状态更改时触发的ios地址栏

ios - 隐藏/显示 UITabBarController 的 .tabBar(用于 Root View Controller )

ios - SKSpriteNode UserInteractionEnabled 不起作用

ios - 有什么方法可以避免 SwiftUI GeometryReader 阻止嵌套 View 在 List 内增长?

ios - 如何修复 TestFlight (iTunes Connect) 中的多个构建错误?

ios - Swift UNUserNotification 不触发声音