iphone - 不确定如何修复此 EXC_BAD_ACCESS 错误

标签 iphone ios objective-c nsstring exc-bad-access

所以我有一个 Task 实体类(核心数据),我正在尝试覆盖其中一个字符串 (timeIntervalString) 的 setter ,以便它可以显示在 TableView 单元格的详细文本标签中。出于某种原因,我收到这样的 EXC_BAD_ACCESS 错误:

enter image description here

[Tasks timeIntervalString] 一直持续到大约 37355...

这是我的代码:

-(NSString *)timeIntervalString{

    NSUInteger seconds = (NSUInteger)round(self.timeInterval);
if ((seconds/3600) == 0){
    if (((seconds/60) % 60) == 1) {
        self.timeIntervalString = [NSString stringWithFormat:@"%u MIN", ((seconds/60) % 60)];
    } else {
        self.timeIntervalString = [NSString stringWithFormat:@"%u MINS", ((seconds/60) % 60)];
    }
} else if ([self.conversionInfo hour] == 1) {
    if (((seconds/60) % 60) == 0){
        self.timeIntervalString = [NSString stringWithFormat:@"%u HR", (seconds/3600)];
    } else if (((seconds/60) % 60) == 1) {
        self.timeIntervalString = [NSString stringWithFormat:@"%u HR %u MIN", (seconds/3600), ((seconds/60) % 60)];
    } else {
        self.timeIntervalString = [NSString stringWithFormat:@"%u HR %u MINS", (seconds/3600), ((seconds/60) % 60)];
    }
} else {
    if (((seconds/60) % 60) == 0) {
        self.timeIntervalString = [NSString stringWithFormat:@"%u HRS ", (seconds/3600)];
    } else if (((seconds/60) % 60) == 1){
        self.timeIntervalString = [NSString stringWithFormat:@"%u HRS %u MIN", (seconds/3600), ((seconds/60) % 60)];
    } else {
        self.timeIntervalString = [NSString stringWithFormat:@"%u HRS %u MINS", (seconds/3600), ((seconds/60) % 60)];
    }
}
return self.timeIntervalString;

有什么想法吗?

最佳答案

return self.timeIntervalString 将递归调用相同的 timeIntervalString 方法。

您可能想要的是return _timeIntervalString

说明:self.timeIntervalString是属性访问器语法糖,它和[self timeIntervalString]是一样的,它会调用-(NSString *)您在此处定义的 timeIntervalString 方法。 return _timeIntervalString 更改将使您能够直接访问实例变量,而不是递归调用属性访问器。这是您在编写的任何自定义属性访问器方法中都应遵循的通用模式。

编辑:根据评论中的讨论,最好将其标记为只读属性并且永远不要实际设置值:

在你的 .h 文件中:

@property (readonly) NSString *timeIntervalString;

在您的 .m 文件中:

-(NSString *)timeIntervalString {
    NSString *value;
    // insert here the body of your timeIntervalString method, as you
    // originally wrote it, but replace all occurences of:
    // self.timeIntervalString = ...
    // with this: value = ...
    return value;
}

关于iphone - 不确定如何修复此 EXC_BAD_ACCESS 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18002392/

相关文章:

iphone - 全局添加一个函数以在整个 iPhone 应用程序中使用

ios - 如何仅存储没有时区和实际时间的日期

iphone - 基于苹果示例代码 TVAnimationsGestures 在基于 UITableView 的 Accordion View 中一次保持一个部分打开

ios - 在 Xcode 5 的存档/配置文件中找不到“File/File.h”(Parse/Parse.h)

ios - 重新加载导航栏 UIBarButtonItem

ios - 在ios中加载对象

iphone ios 在单独的线程中运行

iOS - 向远程通知添加操作。我错过了什么?

iphone - 使用参数 iphone/ipad 处理点击手势

objective-c - Objective-C : How to switch from one Tab bar to another via program