ios - 从另一个对象调用时僵尸 NSString

标签 ios oop exc-bad-access objective-c++ nszombie

我可以在类之间传递基本数据,但是当我尝试从我的 UIApplicationDelegate 传递一个 NSString* 时,我得到一个 EXC_BAD_ACCESS/NSZombie.

为了返回 NSObject,我需要做些什么特别的事情吗?这与线程有关吗? (我认为属性上的 atomic 设置会解决这个问题?)

AppDelegate.h:

@interface AppDelegate : NSObject <UIApplicationDelegate> {
  NSString * currentNoteName;
}
@property (atomic, assign) NSString *currentNoteName;
@end

AppDelegate.m:

- (void)timerCallback:(NSTimer *)timer {
    currentNoteName = [NSString stringWithCString:(tone->freq).c_str() encoding:NSUTF8StringEncoding];

// This works:
    NSLog(@"Current Note Name in timerCallback: %@", currentNoteName);

其他对象.m:

// Returns a Zombie object & EXC_BAD_ACCESS:
NSString *currentNoteName = [appDelegate currentNoteName];

最佳答案

如果不使用 ARC,则必须使用保留属性:

@property (atomic, retain) NSString *currentNoteName;

并使用setter为其分配一个值:

self.currentNoteName = [NSString stringWithCString: ...];

不要忘记在 AppDelegatedealloc 实现中释放这个 ivar 的实例:

- (void) dealloc {
  [currentNoteName release], currentNoteName = nil;
  [super dealloc];
}

关于ios - 从另一个对象调用时僵尸 NSString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8213183/

相关文章:

ios - 堆栈溢出 : Thread 1: EXC_BAD_ACCESS (code=2, 地址=0x16d09aa00)

iphone - 在 ViewController 中设置自定义 UITableViewCell 的 UILabel.text

ios - 标题标签文本颜色在 UIButton 中无法正确设置动画

ios - UIWebView 可以检测到 Javascript 对话框何时将要显示吗?

javascript - 面向对象的Javascript中公共(public)函数和使用原型(prototype)添加的函数有什么区别

c++ - 从另一个构造函数调用构造函数?

c++ - 一个棘手的 OOP 问题,我从来没有想过

ios - NSHourCalendarUnit 和 NSMinuteCalendarUnit 已弃用。如何拆分小时和分钟?

objective-c - didSelectRowAtIndexPath 中的 EXC_BAD_ACCESS

ios - Singleton 中的 NSMutableArrays 不保存值