+1  A: 

NSArray *retVal = [fetchResults retain] should keep everything around for you. It doesn't make a copy, but I expect that's not really what you're trying to do. Your first attempt there should make a copy. They're all prone to leaking if you're not careful though (your second example leaks guaranteed). Are you sure you're not doing something else in the program that makes this part of the code fail?

Here are some options for doing a real copy if that's what you want:

NSArray *retVal = [fetchResults copy];
NSArray *retVal = [[NSArray alloc] initWithArray:fetchResults];

Both of those return retained arrays to you.

Carl Norum
+1  A: 

Are you sure the fetch request is returning data? According to the documentation:

An array of objects that meet the criteria specified by request fetched from the receiver and from the persistent stores associated with the receiver’s persistent store coordinator. If an error occurs, returns nil. If no objects match the criteria specified by request, returns an empty array.

Also, could you show the code where you access the array? Is it in the same method where you're executing the fetch request?

kubi
+5  A: 

You are thrashing; of these lines of code...

NSArray *retVal = [[NSArray alloc] initWithArray:fetchResults];
NSArray *retVal = [[NSArray alloc] initWithArray:[fetchResults copy]];
NSArray *retVal = [[NSArray alloc] initWithArray:[fetchResults retain]];

The latter two are simple leaks. The first is one way of making a copy, but retVal = [fetchResults copy]; is a better way to make a copy.

But, of course, you don't need a copy at all. That isn't the problem. You go on to say that the only thing that doesn't crash is an empty result set.

That indicates one of two things; either your result set is corrupt (unlikely) or you are accessing the result set incorrectly (likely).

The "thrashing" is that you have asked a question about a crash without including either the backtrace of the crash or the location of the crash. Add those and you'll likely get an answer in short order.

(And don't take offense at "thrashing" -- we all do it. Even after 20+ years of Objective-C, I still have to facepalm, step back, and think things through to get away from thrashing.)

bbum
+1  A: 

NSArray *retVal = [[NSArray alloc] initWithArray:fetchResults]; NSArray *retVal = [[NSArray alloc] initWithArray:[fetchResults copy]]; NSArray *retVal = [[NSArray alloc] initWithArray:[fetchResults retain]];

Are you sure that fetchResults contains result? Because there may be a chance that "fetchResults" object itself released and pointing to some garbage location. That is why you are getting crash. Check and inform whether fetchResults is a valid object or not.

Manjunath