将对象返回到ViewController中的方法

时间:2012-02-02 02:22:39

标签: iphone objective-c ios

我正在尝试调用一个返回对象并需要帮助的方法,因为我在调用它时会得到一个EXC_BAD_ACCESS。我试图让一个QuoteMap对象返回到调用它的ViewController。

该方法是addAndReturnQuoteMap,它在标题QuoteMap.h中声明

- (QuoteMap *)addAndReturnQuoteMap:(NSString *)subId withQuoteId:(NSString *)quoteId;

方法本身如下:

- (QuoteMap *)addAndReturnQuoteMap:(NSString *)subId withQuoteId:(NSString *)quoteId {

//FIRST GET A NEW QUOTE_MAP_ID

NSInteger newQuoteMapId = self.getNextQuoteMapId;
NSLog(@"newQuoteMapId = %d", newQuoteMapId);

// THEN TAKE THE QUOTE_MAP_ID, SUBJECT_ID AND QUOTE_ID AND INSERT INTO QUOTE_MAP TABLE

NSLog(@"subId = %@   quoteId = %@", subId, quoteId);

QuotesAppDelegate *appDelegate = (QuotesAppDelegate *)[[UIApplication sharedApplication] delegate];
FMDatabase *database = [FMDatabase databaseWithPath:appDelegate.getDBPath];    

if ([database open]) {
    [database executeUpdate:@"insert into QUOTE_MAP(quote_map_id, quote_id, subject_id) values(?, ?, ?)", 
     newQuoteMapId, subId, quoteId];

    [database close];
}

[database open];

FMResultSet *result_categories = [database executeQuery:@"select * from QUOTE where quote_id = 835"];
[result_categories next];

QuoteMap *qm = [QuoteMap alloc];
qm.quote_map_id = [result_categories stringForColumn:@"QUOTE_MAP_ID"];
qm.quote_id = [result_categories stringForColumn:@"QUOTE_ID"];
qm.subject_id = [result_categories stringForColumn:@"SUBJECT_ID"];
qm.isDirty = NO;

NSLog(@"QuoteMap inserted the quote_map_id of: %@", qm.quote_map_id);
[qm release];

return qm;

};

我在这里从我的AddQuoteViewController调用方法:

    [qm addAndReturnQuoteMap:mySubjectId withQuoteId:quote.quote_id];

我确信我做错了什么是非常愚蠢的,并且会对我可能会有什么方向表示赞赏。

3 个答案:

答案 0 :(得分:2)

您未在init上致电QuoteMap。它应该是:

QuoteMap *qm = [[QuoteMap alloc] init];

如果没有立即调用某种形式的+alloc,您就不应该打电话给-init

答案 1 :(得分:1)

你必须初始化qm而不只是为它分配内存:

QuoteMap *qm = [[QuoteMap alloc] init];

并且不释放返回的对象,因此在此之后它是无效的。让它自动释放。

答案 2 :(得分:1)

将您的代码更改为

QuoteMap *qm = [[QuoteMap alloc] init];
//your code
[qm autorelease];
return qm;