I have a problem here. Or Maybe I'm really tired...
I have a class :
#interface THECLASS : UIViewController <UITableViewDelegate> {
NSMutableArray* param;
}
#property(nonatomic, retain) NSMutableArray* param;
Inside that class I have a method that is called when the user clicks on a UISwitch inside a tableViewCell (I build the params into a IBAction method that is not shwon here) :
#synthesize param;
- (void) changedSelectorValue:(NSIndexPath*)indexPath isOn:(BOOL)isOn {
[self.param addObject:#"eeeee"];
}
This crashes the app with the following log :
2011-02-04 01:31:02.548 Learning Project[3895:207] -[__NSArrayI addObject:]: unrecognized selector sent to instance 0x630c960
2011-02-04 01:31:02.549 Learning Project[3895:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayI addObject:]: unrecognized selector sent to instance 0x630c960'
*** Call stack at first throw:
(
0 CoreFoundation 0x00fc4be9 __exceptionPreprocess + 185
1 libobjc.A.dylib 0x011195c2 objc_exception_throw + 47
2 CoreFoundation 0x00fc66fb -[NSObject(NSObject) doesNotRecognizeSelector:] + 187
3 CoreFoundation 0x00f36366 ___forwarding___ + 966
4 CoreFoundation 0x00f35f22 _CF_forwarding_prep_0 + 50
5 Learning Project 0x00019463 -[ChoixJoursDisponibiliteController changedSelectorValue:isOn:] + 644
6 Learning Project 0x000190db -[ChoixJoursDisponibiliteController clickChangedSelectorValue:] + 307
7 UIKit 0x002f6a6e -[UIApplication sendAction:to:from:forEvent:] + 119
8 UIKit 0x003851b5 -[UIControl sendAction:to:forEvent:] + 67
9 UIKit 0x00387647 -[UIControl(Internal) _sendActionsForEvents:withEvent:] + 527
10 UIKit 0x004c9c6d -[UISwitch _onAnimationDidStop:finished:context:] + 201
11 UIKit 0x00327665 -[UIViewAnimationState sendDelegateAnimationDidStop:finished:] + 294
12 UIKit 0x003274f7 -[UIViewAnimationState animationDidStop:finished:] + 77
13 QuartzCore 0x01eab6cb _ZL23run_animation_callbacksdPv + 278
14 QuartzCore 0x01eab589 _ZN2CAL14timer_callbackEP16__CFRunLoopTimerPv + 157
15 CoreFoundation 0x00fa5fe3 __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 19
16 CoreFoundation 0x00fa7594 __CFRunLoopDoTimer + 1220
17 CoreFoundation 0x00f03cc9 __CFRunLoopRun + 1817
18 CoreFoundation 0x00f03240 CFRunLoopRunSpecific + 208
19 CoreFoundation 0x00f03161 CFRunLoopRunInMode + 97
20 GraphicsServices 0x018f9268 GSEventRunModal + 217
21 GraphicsServices 0x018f932d GSEventRun + 115
22 UIKit 0x0030542e UIApplicationMain + 1160
23 Learning Project 0x00002580 main + 102
24 Learning Project 0x00002511 start + 53
25 ??? 0x00000001 0x0 + 1
)
terminate called after throwing an instance of 'NSException'
param is filled from a caller view by something like :
NSMutableArray* filledArray = [NSMutableArray arrayWithObjects:#"SOME TEXT", nil]
nextController.param = filledArray;
NSLog(#"%#", self.param); just before the crash gives :
2011-02-04 02:01:17.205 Learning Project[4223:207] (
"JOURDISPO_MARDI"
)
Why does this crash ?
The array is there, filled and not nil... It seems well defined... addObject is a NSMutableArray method... I don't understand
I don't show it here but there is the same log with removeObject.
Answer is buried in the comments to the "accepted" answer. I came here from Google and it fixed my problem, so ... to make it clearer, based on #e.James's comment:
When you implement the "NSCopying" protocol, and implement
"copyWithZone", you MUST NOT use "copy" on your internal mutable arrays - this
DOES NOT copy the array (instead, it creates a non-mutable copy).
e.g. from my own code:
// Class: MyClass
#property(nonatomic, retain) NSMutableArray* mutArray;
-(id)copyWithZone:(NSZone *)zone
{
MyClass* other = [[MyClass alloc] init];
// other.mutArray = [self.mutArray copy]; // WRONG!
other.mutArray = [self.mutArray mutableCopy]; // CORRECT!
return other;
}
For some reason you're calling the addObject: method on an instance of NSArray, as the stack trace indicates. Perhaps the synthesized getter of your param object returns an NSArray? Don't use the getter in your method:
- (void) changedSelectorValue:(NSIndexPath*)indexPath isOn:(BOOL)isOn {
[param addObject:#"eeeee"];
}
Ultimately, the error is correct. You're calling a mutating method on an immutable object. Strange enough, in my testing this doesn't cause a compiler error or warning:
NSMutableArray *array = [[NSArray alloc] init];
Edit: Whether you want to believe it or not, somehow the param ivar is being set to an instance of an NSArray. Override the setter:
- (void)setParam:(NSMutableArray *)p {
if (param != p) {
[param release];
param = [p retain];
}
}
Then add a breakpoint on that method, and check to see when an NSArray is being passed in.
Your property is defined as retain, and you say that param is "a filled array from the caller view". This could be your problem.
For example, if you do the following:
NSArray * filledArray = [NSArray arrayWithObjects:..., nil];
theClassInstance.param = filledArray;
You will have retained a non-mutable array.
Edit: To debug the setting of param, you could do the following in your .m:
#dynamic param;
- (NSMutableArray*)param { return param; }
- (void)setParam:(NSMutableArray*)newArray {
NSLog(#"setting new param from class: %#",
NSStringFromClass([newArray class]));
[newArray retain];
[param release];
param = newArray;
}
What does your init method look like? It should look something like this...
- (id)init
{
self = [super init];
self.param = [NSMutableArray array];
return self;
}
After struggling a lot i found the solution for my problem. In my case the problem was,
I have a mutable dictionary and array
#property(strong,nonatomic)NSMutableDictionary *dictInfo;
#property(retain,nonatomic) NSMutableArray *userAccountsList;
And I am adding server array list to userAccountsList array like this
self.dictInfo = [jsonObject valueForKey:#"customerAccountList"];
I have taken another array and adding server array list to that array
array = [self.dictInfo valueForKey:#"banker"];
and finally adding array to userAccountsListArray like this
userAccountsList = [NSMutableArray arrayWithArray:array];
And here adding additional object to array
[userAccountsList addObject:#"Other Account"];//I was getting error here.
[tableViewObj reloadData];
Hope it helps someone. Please vote up if it helps.
Related
I know there have been a ton of questions about the same thing, but so far I haven't been able to apply any solutions to my problem. And I still haven't figured out how to use Instruments.
I'm taking a basic tutorial for an iPhone app and just trying to tweak it slightly (I am new to Objective C). I want it to read from a plist with an array of dicts instead of an array of strings. The table initially displays the data correctly. However whenever I scroll the table up (and off the screen), I am getting Unrecognized Selector exceptions. Just populating employees with NSStrings works fine. I am lost.
Relevant portions of the ViewController:
#interface RootViewController : UITableViewController {
NSMutableArray *employees_;
}
#property (nonatomic, retain) NSMutableArray *employees;
#end
and
#implementation RootViewController
#synthesize employees=employees_;
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *path = [[NSBundle mainBundle] pathForResource:#"Employees" ofType:#"plist"];
NSMutableArray *empArray = [[NSMutableArray alloc] initWithContentsOfFile:path];
employees_ = [empArray valueForKey:#"name"];
[empArray release];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell.
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.textLabel.text = [self.employees objectAtIndex:indexPath.row];//this is where it errors
return cell;
}
- (void)dealloc
{
[employees_ release];
[super dealloc];
}
#end
and plist:
array
dict
key name /key
string Employee One /string
key id /key
string T1234 /string
/dict
dict
key name /key
string Employee Two /string
key id /key
string T5678 /string
/dict
/array
Error that I received:
2011-10-18 20:02:44.313 MyApp[65148:bc03] -[NSCFString objectAtIndex:]: unrecognized selector sent to instance 0x689a050
2011-10-18 20:02:44.316 MyApp[65148:bc03] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSCFString objectAtIndex:]: unrecognized selector sent to instance 0x689a050'
*** Call stack at first throw:
(
0 CoreFoundation 0x00dc25a9 __exceptionPreprocess + 185
1 libobjc.A.dylib 0x00f16313 objc_exception_throw + 44
2 CoreFoundation 0x00dc40bb -[NSObject(NSObject) doesNotRecognizeSelector:] + 187
3 CoreFoundation 0x00d33966 ___forwarding___ + 966
4 CoreFoundation 0x00d33522 _CF_forwarding_prep_0 + 50
5 MyApp 0x00002a96 -[RootViewController tableView:cellForRowAtIndexPath:] + 326
6 UIKit 0x00089b98 -[UITableView(UITableViewInternal) _createPreparedCellForGlobalRow:withIndexPath:] + 634
7 UIKit 0x0007f4cc -[UITableView(UITableViewInternal) _createPreparedCellForGlobalRow:] + 75
8 UIKit 0x000948cc -[UITableView(_UITableViewPrivate) _updateVisibleCellsNow:] + 1561
9 UIKit 0x0008c90c -[UITableView layoutSubviews] + 242
10 QuartzCore 0x016aca5a -[CALayer layoutSublayers] + 181
11 QuartzCore 0x016aeddc CALayerLayoutIfNeeded + 220
12 QuartzCore 0x016540b4 _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 310
13 QuartzCore 0x01655294 _ZN2CA11Transaction6commitEv + 292
14 QuartzCore 0x0165546d _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 99
15 CoreFoundation 0x00da389b __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 27
16 CoreFoundation 0x00d386e7 __CFRunLoopDoObservers + 295
17 CoreFoundation 0x00d011d7 __CFRunLoopRun + 1575
18 CoreFoundation 0x00d00840 CFRunLoopRunSpecific + 208
19 CoreFoundation 0x00d00761 CFRunLoopRunInMode + 97
20 GraphicsServices 0x00ffa1c4 GSEventRunModal + 217
21 GraphicsServices 0x00ffa289 GSEventRun + 115
22 UIKit 0x00022c93 UIApplicationMain + 1160
23 MyApp 0x00002249 main + 121
24 MyApp 0x000021c5 start + 53
)
terminate called throwing an exceptionCurrent language: auto; currently objective-c
(gdb)
There are two potential problems:
You need to make sure the call to employees_ = [empArray valueForKey:#"name"] is actually returning a NSArray
Once one is ruled out, and assuming you are not using ARC, your employees_ ivar is getting released before the table view gets a chance to configure itself. Try
employees_ = [[empArray valueForKey:#"name"] retain];
And then release employees_ in your viewDidUnload & dealloc methods.
Hard to tell it from the stack as it does say your ivar is a NSCFString but it could be just because it is referencing an invalid/garbage memory address. Based on your plist description though, the likely cause on on point #1.
-[NSCFString objectAtIndex:]: unrecognized selector
This means you tried to send the selector (i.e. call the method) objectAtIndex: on an instance of class NSCFString (which is the same as NSString). ("Next Step / Core Foundation String")
You can't do that.
Since you only are calling objectAtIndex: in one place in your above code, it's easy to see where the problem is. (Besides which in your debugger you should be able to see what line it happens on.) You're calling [self.employees objectAtIndex:...]. Obviously you expect self.employees to be an array, but it is a string instead. I don't really know about plist processing, so figuring out why employees got a string and how to make it get an array instead is up to you.
Quick question:
If I use
[someViewController.view addSubView:otherViewController.view];
to add a view. And then use
[otherViewController.view removeFromSuperView]
to remove the view, my app will crash when I call [otherViewController release]
The crash point is in the [super dealloc] line in my dealloc method of otherViewControll class implementation.
otherViewController is a reference to the view controller. I call release after its view has been removeFromSuperView'ed. By the time I call release, it's a valid pointer.
What am I doing wrong here?
otherViewController's dealloc class implementation
- (void)dealloc {
[popVC release];
[photoContainer release];
[photoView release];
[recordName release];
[recordIngr release];
[recordDesc release];
[recordPrice release];
[quantity release];
[pricingLabel release];
[increaseButton release];
[decreaseButton release];
[pricingTableVC release];
[pricingTable release];
[super dealloc]; // <--- crash point
}
updated: call trace
2011-06-04 00:35:05.110 MyApp[2308:207] -[__NSCFType _viewDelegate]: unrecognized selector sent to instance 0x4b6feb0
2011-06-04 00:35:05.124 MyApp[2308:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFType _viewDelegate]: unrecognized selector sent to instance 0x4b6feb0'
*** Call stack at first throw:
(
0 CoreFoundation 0x00dd75a9 __exceptionPreprocess + 185
1 libobjc.A.dylib 0x00f2b313 objc_exception_throw + 44
2 CoreFoundation 0x00dd90bb -[NSObject(NSObject) doesNotRecognizeSelector:] + 187
3 CoreFoundation 0x00d48966 ___forwarding___ + 966
4 CoreFoundation 0x00d48522 _CF_forwarding_prep_0 + 50
5 UIKit 0x00379051 -[UIViewController dealloc] + 128
6 MyApp 0x00009b26 -[RecordDetailViewController dealloc] + 797
7 MyApp 0x00004744 __-[RecordRootViewController bringUpNextRecordDetail:isNext:]_block_invoke_2 + 77
8 UIKit 0x002f7fb9 -[UIViewAnimationState sendDelegateAnimationDidStop:finished:] + 294
9 UIKit 0x002f7e4b -[UIViewAnimationState animationDidStop:finished:] + 77
10 QuartzCore 0x01d7b99b _ZL23run_animation_callbacksdPv + 278
11 QuartzCore 0x01d20651 _ZN2CAL14timer_callbackEP16__CFRunLoopTimerPv + 157
12 CoreFoundation 0x00db88c3 __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 19
13 CoreFoundation 0x00db9e74 __CFRunLoopDoTimer + 1220
14 CoreFoundation 0x00d162c9 __CFRunLoopRun + 1817
15 CoreFoundation 0x00d15840 CFRunLoopRunSpecific + 208
16 CoreFoundation 0x00d15761 CFRunLoopRunInMode + 97
17 GraphicsServices 0x0172e1c4 GSEventRunModal + 217
18 GraphicsServices 0x0172e289 GSEventRun + 115
19 UIKit 0x002d5c93 UIApplicationMain + 1160
20 MyApp 0x0000200c main + 102
21 MyApp 0x00001f9d start + 53
)
terminate called after throwing an instance of 'NSException'
Update:
in -viewDidLoad, I have a gesture recognizer:
{
UISwipeGestureRecognizer *leftSwipeGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(showNextRecod:)];
[leftSwipeGestureRecognizer setDirection:(UISwipeGestureRecognizerDirectionLeft)];
[self.view addGestureRecognizer:leftSwipeGestureRecognizer];
[leftSwipeGestureRecognizer release];
}
I tried to use a Button to call -(IBAction) showNextRecod, it won't crash!! Only when I use the gesture to call the same method, it would crash
Regards
Leo
When you add a view controller's view as a subview to another view, you are only retaining it's view in memory and not the controller itself. Therefore, you must retain the view controller somewhere else (most likely make it a property)
Does that make sense?
In your gesture selector showNextRecod:
you should remove your target [pGestureRecognizer removeTarget:nil action:NULL];
#leo
You are just adding otherViewController.view in someViewController.view.
Just adding view not allocating it, then just remove it from your view.
Im not getting why you are using
[otherViewController release]
when you are not allocating it same view.
For sure you can log otherViewController.view count. See how much retain count for that view you are getting.
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Thread" inManagedObjectContext:managedObjectContext];
That line doesn't seem to work anymore (I'm pretty sure its that line).
I can't seem to work out whats the problem. The application worked perfectly on Xcode with iOS 4.1 and now crashes with this error in the console:
2010-12-07 17:12:27.552 SMSApp[9222:207] +[ persistentStoreCoordinator]: unrecognized selector sent to class 0x5b14580
2010-12-07 17:12:27.553 SMSApp[9222:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+[ persistentStoreCoordinator]: unrecognized selector sent to class 0x5b14580'
*** Call stack at first throw:
(
0 CoreFoundation 0x01547be9 __exceptionPreprocess + 185
1 libobjc.A.dylib 0x0169c5c2 objc_exception_throw + 47
2 CoreFoundation 0x015497bb +[NSObject(NSObject) doesNotRecognizeSelector:] + 187
3 CoreFoundation 0x014b9366 ___forwarding___ + 966
4 CoreFoundation 0x014b8f22 _CF_forwarding_prep_0 + 50
5 CoreData 0x00e6f3ca +[NSEntityDescription entityForName:inManagedObjectContext:] + 42
6 SMSApp 0x000046b9 -[MessagesRootViewController reloadMessages:] + 146
7 SMSApp 0x00004a09 -[MessagesRootViewController viewDidLoad] + 85
8 UIKit 0x0052265e -[UIViewController view] + 179
9 UIKit 0x00520a57 -[UIViewController contentScrollView] + 42
10 UIKit 0x00531201 -[UINavigationController _computeAndApplyScrollContentInsetDeltaForViewController:] + 48
11 UIKit 0x0052f831 -[UINavigationController _layoutViewController:] + 43
12 UIKit 0x00530b4c -[UINavigationController _startTransition:fromViewController:toViewController:] + 524
13 UIKit 0x0052b606 -[UINavigationController _startDeferredTransitionIfNeeded] + 266
14 UIKit 0x00643e01 -[UILayoutContainerView layoutSubviews] + 226
15 QuartzCore 0x010b4451 -[CALayer layoutSublayers] + 181
16 QuartzCore 0x010b417c CALayerLayoutIfNeeded + 220
17 QuartzCore 0x010ad37c _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 310
18 QuartzCore 0x010ad0d0 _ZN2CA11Transaction6commitEv + 292
19 UIKit 0x0047719f -[UIApplication _reportAppLaunchFinished] + 39
20 UIKit 0x00477659 -[UIApplication _runWithURL:payload:launchOrientation:statusBarStyle:statusBarHidden:] + 690
21 UIKit 0x00481db2 -[UIApplication handleEvent:withNewEvent:] + 1533
22 UIKit 0x0047a202 -[UIApplication sendEvent:] + 71
23 UIKit 0x0047f732 _UIApplicationHandleEvent + 7576
24 GraphicsServices 0x01b2ca36 PurpleEventCallback + 1550
25 CoreFoundation 0x01529064 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 52
26 CoreFoundation 0x014896f7 __CFRunLoopDoSource1 + 215
27 CoreFoundation 0x01486983 __CFRunLoopRun + 979
28 CoreFoundation 0x01486240 CFRunLoopRunSpecific + 208
29 CoreFoundation 0x01486161 CFRunLoopRunInMode + 97
30 UIKit 0x00476fa8 -[UIApplication _run] + 636
31 UIKit 0x0048342e UIApplicationMain + 1160
32 SMSApp 0x000025c4 main + 102
33 SMSApp 0x00002555 start + 53
)
terminate called after throwing an instance of 'NSException'
Any idea where this error is coming from or what is causing it?
Just to let you know as well, upgrading to XCode with iOS 4.2 caused some of the files to be deleted from my project. I don't know why this was, whether it was because they were linked files and not actually in the folder I dunno.
Any ideas?
Thanks
// EDIT
This method is in the AppDelegate:
- (NSManagedObjectContext *)managedObjectContext {
if (managedObjectContext_ != nil) {
return managedObjectContext_;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
managedObjectContext_ = [[NSManagedObjectContext alloc] init];
[managedObjectContext_ setPersistentStoreCoordinator:coordinator];
}
return managedObjectContext_;
}
// EDIT AGAIN
- (void)reloadMessages:(NSNotification *)notification {
NSLog(#"RECIEVED NEW MESSAGES TO MessagesRootViewController");
NSLog(#"%#",managedObjectContext);
// we need to get the threads from the database...
NSFetchRequest *theReq = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Thread" inManagedObjectContext:self.managedObjectContext];
[theReq setEntity:entity];
threads = [NSArray arrayWithArray:[managedObjectContext executeFetchRequest:theReq error:nil]];
[self.tableView performSelectorOnMainThread:#selector(reloadData) withObject:nil waitUntilDone:NO];
if(notification != nil){ // if its been caused by a notification
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"New Message" message:#"A new message has been received" delegate:nil cancelButtonTitle:#"Thanks" otherButtonTitles:nil];
[alert performSelectorOnMainThread:#selector(show) withObject:nil waitUntilDone:NO];
[alert release];
}
}
// EDIT 3
If I put this code in the applicationDidFinishLoading of my app delegate it works fine!
NSFetchRequest *theReq = [[NSFetchRequest alloc] init];
NSEntityDescription *theEntity = [NSEntityDescription entityForName:#"Thread" inManagedObjectContext:self.managedObjectContext];
[theReq setEntity:theEntity];
NSArray *theThreads = [NSArray arrayWithArray:[self.managedObjectContext executeFetchRequest:theReq error:nil]];
After having a quick look at your code I think I found a couple of parts that needed attention. I'll try and break them down below:
SMSAppAppDelegate
1) Notice that in your interface file, you declare your CoreData variables with an underscore at the end of the variable name. Then you create properties for each of the ivar without the underscore. That is all fine as long as you #synthesize them making the correct assignment, which seems to be missing from your implementation:
#synthesize managedObjectContext=managedObjectContext_;
#synthesize managedObjectModel=managedObjectModel_;
#synthesize persistentStoreCoordinator=persistentStoreCoordinator_;
DownloadContacts
1) In this class you are calling the managedObjectContext directly through the variable. I wouldn't recommend that but this is not your actual problem. Notice that you release the managedObjectContext on dealloc even though you have no ownership of it!
2) What I would do in this case is declare a property for the context and always access it via the property. Also if you rename your instance variable to include an underscore at the end you are minimising your chances of accessing it directly (i.e. without using self.) and it will make it easier for you to find where in this class you are actually doing that (there are a couple of places from memory).
So in your interface file, rename managedObjectContext ivar and declare a property:
NSManagedObjectContext *managedObjectContext_;
...
#property (nonatomic, retain) NSManagedObjectContext managedObjectContext;
And don't forget to make the assignment on #sythesize and release on dealloc, since you are using a retain property:
#synthesize managedObjectContext=managedObjectContext_;
...
[managedObjectContext_ release];
Then if you try and compile you will get two or three errors of unrecognised instance variable which is where you have to go and change it to self.managedObjectContext
MessagesRootViewController
And finally I'd recommend you go through the same process in your MessagesRootViewController but this one should still work fine as is!
See how you go and let me know if any of the above is not clear!
Cheers,
Rog
I'm assuming you're doing something like:
[ClassName persistentStoreCoordinator]
Make sure ClassName is defined and has the persistentStoreCoordinator class method. Perhaps the file that did these things got deleted?
Matt
Your database might be corrupted, try resetting the iOS simulator
by clicking on iOS Simulator>Reset contents and settings.
Edit:
It looks like you're trying to call a selector that doesn't exist. Try figuring out which files were deleted, as it seems like you have a method that is called that can't be found at runtime. Did your core data classes get erased, maybe?
Edit: This was all caused by a typo in my Other Link Flags setting. See my answer below for more information.
I'm attempting to mock a UIWebView so that I can verify that methods on it are called during a test of an iOS view controller. I'm using an OCMock static library built from SVN revision 70 (the most recent as of the time of this question), and Google Toolbox for Mac's (GTM) unit testing framework, revision 410 from SVN. I'm getting the following error when the view controller attempts to call the expected method.
Test Case '-[FirstLookViewControllerTests testViewDidLoad]' started.
2010-11-11 07:32:02.272 Unit Test[38367:903] -[NSInvocation getArgumentAtIndexAsObject:]: unrecognized selector sent to instance 0x6869ea0
2010-11-11 07:32:02.277 Unit Test[38367:903] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSInvocation getArgumentAtIndexAsObject:]: unrecognized selector sent to instance 0x6869ea0'
*** Call stack at first throw:
(
0 CoreFoundation 0x010cebe9 __exceptionPreprocess + 185
1 libobjc.A.dylib 0x012235c2 objc_exception_throw + 47
2 CoreFoundation 0x010d06fb -[NSObject(NSObject) doesNotRecognizeSelector:] + 187
3 CoreFoundation 0x01040366 ___forwarding___ + 966
4 CoreFoundation 0x0103ff22 _CF_forwarding_prep_0 + 50
5 Unit Test 0x0000b29f -[OCMockRecorder matchesInvocation:] + 216
6 Unit Test 0x0000c1c1 -[OCMockObject handleInvocation:] + 111
7 Unit Test 0x0000c12a -[OCMockObject forwardInvocation:] + 43
8 CoreFoundation 0x01040404 ___forwarding___ + 1124
9 CoreFoundation 0x0103ff22 _CF_forwarding_prep_0 + 50
10 Unit Test 0x0000272a -[MyViewController viewDidLoad] + 100
11 Unit Test 0x0000926c -[MyViewControllerTests testViewDidLoad] + 243
12 Unit Test 0x0000537f -[SenTestCase invokeTest] + 163
13 Unit Test 0x000058a4 -[GTMTestCase invokeTest] + 146
14 Unit Test 0x0000501c -[SenTestCase performTest] + 37
15 Unit Test 0x000040c9 -[GTMIPhoneUnitTestDelegate runTests] + 1413
16 Unit Test 0x00003a87 -[GTMIPhoneUnitTestDelegate applicationDidFinishLaunching:] + 197
17 UIKit 0x00309253 -[UIApplication _callInitializationDelegatesForURL:payload:suspended:] + 1252
18 UIKit 0x0030b55e -[UIApplication _runWithURL:payload:launchOrientation:statusBarStyle:statusBarHidden:] + 439
19 UIKit 0x0030aef0 -[UIApplication _run] + 452
20 UIKit 0x0031742e UIApplicationMain + 1160
21 Unit Test 0x0000468c main + 104
22 Unit Test 0x000026bd start + 53
23 ??? 0x00000002 0x0 + 2
)
terminate called after throwing an instance of 'NSException'
/Users/gjritter/src/google-toolbox-for-mac-read-only/UnitTesting/RunIPhoneUnitTest.sh: line 151: 38367 Abort trap "$TARGET_BUILD_DIR/$EXECUTABLE_PATH" -RegisterForSystemEvents
My test code is:
- (void)testViewDidLoad {
MyViewController *viewController = [[MyViewController alloc] init];
id mockWebView = [OCMockObject mockForClass:[UIWebView class]];
[[mockWebView expect] setDelegate:viewController];
viewController.webView = mockWebView;
[viewController viewDidLoad];
[mockWebView verify];
[mockWebView release];
}
My view controller code is:
- (void)viewDidLoad {
[super viewDidLoad];
webView.delegate = self;
}
I did find that the test would run successfully if I instead used:
- (void)testViewDidLoad {
MyViewController *viewController = [[MyViewController alloc] init];
id mockWebView = [OCMockObject partialMockForObject:[[UIWebView alloc] init]];
//[[mockWebView expect] setDelegate:viewController];
viewController.webView = mockWebView;
[viewController viewDidLoad];
[mockWebView verify];
[mockWebView release];
}
However, as soon as I added the expectation that is commented out, the error returned when using the partial mock.
I have other tests that are successfully using mocks in the same project.
Any ideas? Is mocking of UIKit objects supported by OCMock?
Edit: Based on advice in the answer below, I tried the following test, but I'm getting the same error:
- (void)testViewDidLoadLoadsWebView {
MyViewController *viewController = [[MyViewController alloc] init];
UIWebView *webView = [[UIWebView alloc] init];
// This test fails in the same fashion with or without the next line commented
//viewController.view;
id mockWebView = [OCMockObject partialMockForObject:webView];
// When I comment out the following line, the test passes
[[mockWebView expect] loadRequest:[OCMArg any]];
viewController.webView = mockWebView;
[viewController viewDidLoad];
[mockWebView verify];
[mockWebView release];
}
UIKit classes are mysterious beasts, and I've found that mucking around with mocking them can lead to hours of debugging fun. That said, I've found that with a little patience you can make it work.
The first thing I notice with your code is that your controller doesn't load its view in your test. I generally make sure to always force the view to load before any tests run. That, of course, means you can't write expectations for the initialization of your web view, but in this case you don't really need to. You could do this:
- (void)testViewDidLoadSetsWebViewDelegateToSelf {
MyViewController *viewController = [[MyViewController alloc] init];
// Force the view to load
viewController.view;
assertThat(controller.webView.delegate, equalTo(controller));
}
That said, if you do want to then subsequently mock the web view, I would recommend using a partial mock for the existing web view:
- (void)testWebViewDoesSomething {
MyViewController *viewController = [[MyViewController alloc] init];
// Force the view to load
viewController.view;
id mockWebView = [OCMockObject partialMockForObject:controller.webView];
[[mockWebView expect] someMethod];
[controller doWhatever];
[mockWebView verify];
}
In fact, I've found it's best to always use a partial mock for any UIView subclass. If you create a full mock of a UIView it will almost always blow up messily when you try to do something view-related with it, such as add it to a superview.
This turned out to be one of those off by one character issues that you don't notice until you've looked at it a few dozen times.
Per this post on the OCMock forums, I had set my Other Linker Flags for my unit test target to -ObjC -forceload $(PROJECT_DIR)/Libraries/libOCMock.a. This is wrong; -forceload should have been -force_load. Once I fixed this typo, my tests worked.
I grabbed the crash log from the iPhone:
Exception Type: EXC_BAD_ACCESS (SIGBUS)
Exception Codes: KERN_PROTECTION_FAILURE at 0x0000000c
Crashed Thread: 0
Thread 0 Crashed:
0 libobjc.A.dylib 0x30011940 objc_msgSend + 20
1 CoreFoundation 0x30235f1e CFRelease + 98
2 UIKit 0x308f4974 -[UIImage dealloc] + 36
3 CoreFoundation 0x30236b72 -[NSObject release] + 28
4 UIKit 0x30a00298 FlushNamedImage + 64
5 CoreFoundation 0x30250a20 CFDictionaryApplyFunction + 124
6 UIKit 0x30a0019c _UISharedImageFlushAll + 196
7 UIKit 0x30a00730 +[UIImage(UIImageInternal) _flushCacheOnMemoryWarning:] + 8
8 Foundation 0x3054dc7a _nsnote_callback + 178
9 CoreFoundation 0x3024ea52 _CFXNotificationPostNotification + 298
10 Foundation 0x3054b854 -[NSNotificationCenter postNotificationName:object:userInfo:] + 64
11 Foundation 0x3054dbba -[NSNotificationCenter postNotificationName:object:] + 14
12 UIKit 0x30a00708 -[UIApplication _performMemoryWarning] + 60
13 UIKit 0x30a006a0 -[UIApplication _receivedMemoryNotification] + 128
14 UIKit 0x30a005d0 _memoryStatusChanged + 56
15 CoreFoundation 0x30217410 __CFNotificationCenterDarwinCallBack + 20
16 CoreFoundation 0x3020d0aa __CFMachPortPerform + 72
17 CoreFoundation 0x30254a70 CFRunLoopRunSpecific + 2296
18 CoreFoundation 0x30254164 CFRunLoopRunInMode + 44
19 GraphicsServices 0x3204529c GSEventRunModal + 188
20 UIKit 0x308f0374 -[UIApplication _run] + 552
21 UIKit 0x308eea8c UIApplicationMain + 960
...
...
From my previous question, Can somebody give me a hand about this stacktrace in iPhone app?, I have changed my codes mainly around UIImage part. I now use [[UIImage alloc] initWithContentsOfFile ... ]. No more [UIImage imageNamed: ... ] or the like. The portion is below.
//this is a method of a subclass of UIImageView.
- (void) reviewImage: (bool) review{
NSString* st;
if (review){
NSString* origin = [NSString stringWithString: [[ReviewCardManager getInstance] getCardImageString:chosenIndex]];
NSString* stt = [origin substringToIndex: [origin length]-4];
st = [[NSString alloc] initWithString: stt];
if (myImageFlipped == nil)
myImageFlipped = [[UIImage alloc] initWithContentsOfFile: [[NSBundle mainBundle] pathForResource:st ofType:#"png"]];
[self setImage:myImageFlipped];
if (notRotated){
self.transform = CGAffineTransformRotate(self.transform, [MyMath radf:rotate]);
notRotated = false;
}
}else{
st = [[NSString alloc] initWithFormat:#"sc%d", chosenNumber];
if (myImage == nil)
myImage = [[UIImage alloc] initWithContentsOfFile: [[NSBundle mainBundle] pathForResource:st ofType:#"png"]];
[self setImage:myImage];
if (notRotated){
self.transform = CGAffineTransformRotate(self.transform, [MyMath radf:rotate]);
notRotated = false;
}
}
[st release];
}
I also have the UIImage already retained in the property.
#property (nonatomic, retain) UIImage* myImage, *myImageFlipped;
Memory Leaks have also been taken cared of. These variables are release in dealloc method.
I thought that I have successfully killed the bug, but it seems that I still have a rare occuring bug problem.
Based on the crash log, my application yells out "performMemoryWarning". I am just "alloc"-ing 13 .png images with the size 156 x 272. I'm confused. Those images shouldn't take that much memory to the point that it exceeds iPhone's RAM. Or is there something I am overlooking? Please advise.
To help you with memory issues and UIImages, you might want to use the imageNamed convience method of UIImage, from the docs:
This method looks in the system caches for an image object with the specified name and returns that object if it exists. If a matching image object is not already in the cache, this method loads the image data from the specified file, caches it, and then returns the resulting object.
Alternatively, you might want to go this route if you still run into memory issues after switching to UIImage imageNamed, because there are some downsides to using the convinience method.
The problem is solved. I forgot to change UIImage at one place. Now, all UIImages are truly "alloc", no more autorelease.
FYI, if you are using [UIImage imageNamed: ... ], use "Simulate Memory Warning" on iPhone Simulator to see whether you are having a problem with it when the real device is low on memory.