我已經定義了一個結構,並且想將它的一個值賦給一個NSMutableDictionary。當我嘗試時,我得到一個EXC_BAD_ACCESS。下面是代碼:什麼是結構中的NSString?
//in .h file
typedef struct {
NSString *valueOne;
NSString *valueTwo;
} myStruct;
myStruct aStruct;
//in .m file
- (void)viewDidLoad {
[super viewDidLoad];
aStruct.valueOne = @"firstValue";
}
//at some later time
[myDictionary setValue:aStruct.valueOne forKey:@"key1"]; //dies here with EXC_BAD_ACCESS
這是在調試器控制檯輸出:
(gdb) p aStruct.valueOne
$1 = (NSString *) 0xf41850
有沒有辦法告訴什麼aStruct.valueOne的價值是什麼?
既然是NSString,爲什麼字典有這樣的問題呢?
-------------編輯-------------
此編輯基於下面的一些評論。
該問題似乎出現在結構內存分配中。正如其中一條評論所述,我沒有將結構值賦給viewDidLoad中的字典的問題。問題是,後來我遇到了一個關於結構的問題。就在錯誤之前,我做的:
po aStruct.oneValue
Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_PROTECTION_FAILURE at address: 0x00000000
0x9895cedb in objc_msgSend()
The program being debugged was signaled while in a function called from GDB.
GDB has restored the context to what it was before the call.
To change this behavior use "set unwindonsignal off"
Evaluation of the expression containing the function (_NSPrintForDebugger) will be abandoned.
這只是EXC_BAD_ACCESS之前發生:
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MM-dd-yy_HH-mm-ss-A"];
NSString *date = [formatter stringFromDate:[NSDate date]];
[formatter release];
aStruct.valueOne =日期;
所以內存問題最有可能在我發佈格式化程序。日期var沒有保留。我應該做的
NSString *date = [[formatter stringFromDate:[NSDate date]] retain];
哪些工作,但然後我留下了內存泄漏。
EXC_BAD_ACCESS與取消引用解除分配的對象(或未初始化的對象)有關。你確定你初始化了'myDictionary'還是沒有釋放'myStruct'? – notnoop 2009-12-29 06:28:15
我已經更新了OP。請在「編輯」條目後查看 – 4thSpace 2009-12-29 07:53:46
請注意,如果使用ARC Objective-C對象在結構或聯合中被禁止 – elitalon 2013-01-23 17:47:56