I have two modes - Mode 1 and Mode 2 which can be switched by a central button. Switch between modes allows user to see two different types of clustered annotations.
I can switch from Mode 1 to Mode 2 easily, but when I switch back to Mode 1 I'm getting this nasty error
-[__NSCFDictionary componentsSeparatedByString:]: unrecognized selector sent to instance 0x7fb1308cca50
I'm opening my code and in the TBClusteredAnnotations.m (script I'm using for clusterization). I have the following snippet of code relating to componentsSeparatedByString:
TBQuadTreeNodeData TBDataFromLine(NSString *line)
{
NSString *separator=#">>>>>>>>";
NSArray *components = [line componentsSeparatedByString: separator];
double latitude = [components[0] doubleValue];
double longitude = [components[1] doubleValue];
TBUserInfo* userInfo = malloc(sizeof(TBUserInfo));
NSString *userName = [components[2] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
userInfo->userId = malloc(sizeof(char) * userName.length + 1);
strncpy(userInfo->userId, [userName UTF8String], userName.length + 1);
NSString *userId = [components [3] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
userInfo->userImage = malloc(sizeof(char) * userId.length + 1);
strncpy(userInfo->userImage, [userId UTF8String], userId.length + 1);
return TBQuadTreeNodeDataMake(latitude, longitude, userInfo);
}
but I'm loading my annotations with the following code in the MainViewController:
-(void)annotationsmode1:(NSMutableArray*)marr
{
if(marr.count>0)
{
NSMutableArray *newMarr1=[NSMutableArray new];
NSString *separatestuff=#">>>>>>>>";
for(NSMutableDictionary *dic in marr)
{
NSString *newStr=[NSString stringWithFormat:#"%#%#",[dic[#"latitude"] isEqualToString:#""]?#" ":dic[#"latitude"],separatestuff];
newStr=[NSString stringWithFormat:#"%#%#%#",newStr,[dic[#"longitude"] isEqualToString:#""]?#" ":dic[#"longitude"],separatestuff];
newStr=[NSString stringWithFormat:#"%#%#%#",newStr,[dic[#"id"] isEqualToString:#""]?#" ":dic[#"id"],separatestuff];
newStr=[NSString stringWithFormat:#"%#%#",newStr,[dic[#"image"] isEqualToString:#""]?#" ":dic[#"image"]];
[newMarr1 addObject:newStr];
}
//NSLog(#"NEW Array: %#",newMarr);
[self.coordinateQuadTree buildTree:newMarr1];
}
}
-(void)annotationsmode2:(NSMutableArray*)marr
{
if(marr.count>0)
{
NSMutableArray *newMarr=[NSMutableArray new];
NSString *separatestuff2=#">>>>>>>>";
for(NSMutableDictionary *dic in marr)
{
NSString *newStr=[NSString stringWithFormat:#"%#%#",[dic[#"lat"] isEqualToString:#""]?#" ":dic[#"lat"],separatestuff2];
newStr=[NSString stringWithFormat:#"%#%#%#",newStr,[dic[#"lang"] isEqualToString:#""]?#" ":dic[#"lang"],separatestuff2];
newStr=[NSString stringWithFormat:#"%#%#%#",newStr,[dic[#"id"] isEqualToString:#""]?#" ":dic[#"id"],separatestuff2];
newStr=[NSString stringWithFormat:#"%#%#",newStr,[dic[#"image"] isEqualToString:#""]?#" ":dic[#"image"]];
[newMarr addObject:newStr];
}
//NSLog(#"NEW Array: %#",newMarr);
[self.coordinateQuadTree buildTree:newMarr];
}
}
UPDATE: This is the block of code where the TBDataFromLine is used
- (void)buildTree:(NSMutableArray *)lines
{
#autoreleasepool {
NSInteger count = lines.count - 1;
TBQuadTreeNodeData *dataArray = malloc(sizeof(TBQuadTreeNodeData) * count);
for (NSInteger i = 0; i < count; i++) {
dataArray[i] = TBDataFromLine(lines[i]);
}
//TBBoundingBox world = TBBoundingBoxMake(19, -166, 72, -53);
TBBoundingBox world = TBBoundingBoxMake(0,0,100,100);
_root = TBQuadTreeBuildWithData(dataArray, count, world, 4);
}
}
I've been working on this issue for hours now and still have no clue.
UPDATE: Here is the debugger's log I'm getting
2015-06-20 19:40:23.759 MapProject[13426:395344] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary componentsSeparatedByString:]: unrecognized selector sent to instance 0x7fdf93775680'
*** First throw call stack:
(
0 CoreFoundation 0x0000000112699c65 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x00000001121c3bb7 objc_exception_throw + 45
2 CoreFoundation 0x00000001126a10ad -[NSObject(NSObject) doesNotRecognizeSelector:] + 205
3 CoreFoundation 0x00000001125f713c ___forwarding___ + 988
4 CoreFoundation 0x00000001125f6cd8 _CF_forwarding_prep_0 + 120
5 MapProject 0x000000010f469ac4 TBDataFromLine + 84
6 MapProject 0x000000010f46a36f -[TBCoordinateQuadTree buildTree:] + 191
7 MapProject 0x000000010f3d2503 -[MMViewController findSpot:] + 771
8 UIKit 0x0000000110a52da2 -[UIApplication sendAction:to:from:forEvent:] + 75
9 UIKit 0x0000000110b6454a -[UIControl _sendActionsForEvents:withEvent:] + 467
10 UIKit 0x0000000110b63919 -[UIControl touchesEnded:withEvent:] + 522
11 UIKit 0x0000000110a9f998 -[UIWindow _sendTouchesForEvent:] + 735
12 UIKit 0x0000000110aa02c2 -[UIWindow sendEvent:] + 682
13 UIKit 0x0000000110a66581 -[UIApplication sendEvent:] + 246
14 UIKit 0x0000000110a73d1c _UIApplicationHandleEventFromQueueEvent + 18265
15 UIKit 0x0000000110a4e5dc _UIApplicationHandleEventQueue + 2066
16 CoreFoundation 0x00000001125cd431 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
17 CoreFoundation 0x00000001125c32fd __CFRunLoopDoSources0 + 269
18 CoreFoundation 0x00000001125c2934 __CFRunLoopRun + 868
19 CoreFoundation 0x00000001125c2366 CFRunLoopRunSpecific + 470
20 GraphicsServices 0x000000011444da3e GSEventRunModal + 161
21 UIKit 0x0000000110a51900 UIApplicationMain + 1282
22 MapProject 0x000000010f474c2f main + 111
23 libdyld.dy
)
libc++abi.dylib: terminating with uncaught exception of type NSException
Add an Exception break point and it will take to exactly to that line where that crash is happening. Also check 'line' cause it is changed to dictionary but you code expect it
to be a string
There is no [] operator on NSArray or NSMutableArray.
You need this:
for (NSInteger i = 0; i < count; i++) {
dataArray[i] = TBDataFromLine([lines objectAtIndex:i]);
}
Using [] on NSArray* effectively acted like "lines" was really a pointer to an array of NSMutableArray instances, whereas you wanted to get one of the items out of the array to which it pointed.
Related
I am developing iOS application. Value store on Array, but when I run app, its crashes with array index out of bounds. Please Help and Thanks in advance..
Code:
daysOfWeek = [NSArray arrayWithObjects:#"Monday",#"Tuesday",#"Wednesday",#"Thursday",#"Friday",#"Saturday",#"Sunday", nil];
for (int i = 0; i<= [_daysOfWeek count]; i++) {
_mondayView=[[UIView alloc]initWithFrame:CGRectMake(45, 300 , 830, 30.0)];
[_mondayView setBackgroundColor:[UIColor colorWithRed:190.0/255.0 green:190.0/255.0 blue:194.0/255.0 alpha:1.0]];
[_weeklyView addSubview:_mondayView];
UILabel *daysLabel = [[UILabel alloc]initWithFrame:CGRectMake(65.0f, 300.0f, 120.0f, 30.0f)];
daysLabel.backgroundColor = [UIColor blueColor];
daysLabel.text = [NSString stringWithFormat:#"%#",[_daysOfWeek objectAtIndex:i]];
[_weeklyView addSubview:daysLabel];
}
Crash Log:
2016-11-14 11:48:41.266 FH Harvey[1839:67640] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayI objectAtIndex:]: index 7 beyond bounds [0 .. 6]'
*** First throw call stack:
(
0 CoreFoundation 0x000000011101934b __exceptionPreprocess + 171
1 libobjc.A.dylib 0x000000011065d21e objc_exception_throw + 48
2 CoreFoundation 0x0000000110f53eeb -[__NSArrayI objectAtIndex:] + 155
3 FH Harvey 0x000000010fe1ee62 -[FHWeeklyViewController viewDidLoad] + 1026
4 UIKit 0x00000001115ddc99 -[UIViewController loadViewIfRequired] + 1258
5 UIKit 0x00000001115e4102 -[UIViewController __viewWillAppear:] + 118
6 UIKit 0x000000011160efbf -[UINavigationController _startCustomTransition:] + 1290
7 UIKit 0x000000011161fc34 -[UINavigationController _startDeferredTransitionIfNeeded:] + 697
8 UIKit 0x0000000111620dc7 -[UINavigationController __viewWillLayoutSubviews] + 58
9 UIKit 0x0000000111817d6f -[UILayoutContainerView layoutSubviews] + 223
10 UIKit 0x0000000111500f50 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 1237
11 QuartzCore 0x000000010ffbdcc4 -[CALayer layoutSublayers] + 146
12 QuartzCore 0x000000010ffb1788 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 366
13 QuartzCore 0x000000010ffb1606 _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24
14 QuartzCore 0x000000010ff3f680 _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 280
15 QuartzCore 0x000000010ff6c767 _ZN2CA11Transaction6commitEv + 475
16 UIKit 0x0000000111435a97 _UIApplicationFlushRunLoopCATransactionIfTooLate + 206
17 UIKit 0x0000000111c456e0 __handleEventQueue + 5672
18 CoreFoundation 0x0000000110fbe311 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
19 CoreFoundation 0x0000000110fa359c __CFRunLoopDoSources0 + 556
20 CoreFoundation 0x0000000110fa2a86 __CFRunLoopRun + 918
21 CoreFoundation 0x0000000110fa2494 CFRunLoopRunSpecific + 420
22 GraphicsServices 0x00000001163a0a6f GSEventRunModal + 161
23 UIKit 0x000000011143c964 UIApplicationMain + 159
24 FH Harvey 0x000000010fe221bf main + 111
25 libdyld.dylib 0x000000011491368d start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
The problem is with your for loop. Array index start with 0 so change your for loop to:
for (int i = 0; i < [_daysOfWeek count]; i++) {
You are using i<=[_daysOfWeek count] that is the reason you are getting index 7 beyond bounds [0 .. 6] crash.
Instead of using for loop you can use for each loop and it easy to implement and it will never cause you index out of bound crash.
for (NSString* str in _daysOfWeek) {
NSLog(#"%#",str);
}
DEEPAK kumar just verify your logic. Your array having 7 values and you are iterating it 8 times. Just change the logic
for (int i = 0; i < [_daysOfWeek count]; i++)
or
use for each loop as Nirav D describes (most optimized way).
Happy coding..
Just changing you for loop logic from i <= [_daysOfWeek count] to i < [_daysOfWeek count] should resolve your problem. However, to avoid mistakes like this in future, I suggest you to use enumerateObjectsUsingBlock method of NSArray. It can be done in the following way:
NSArray *daysOfWeek = [NSArray arrayWithObjects:#"Monday",#"Tuesday",#"Wednesday",#"Thursday",#"Friday",#"Saturday",#"Sunday", nil];
[daysOfWeek enumerateObjectsUsingBlock:^(NSString* _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
}];
Please write :
for (int i = 0; i < [_daysOfWeek count]; i++)
It will help you.
I'm working on an iOS app with collectionView in objective-c and I have an error.
Below code is for feeding each cell with data(image in this case).
I pick up an image name from two dimensional array in Model class, and display it.
I made up a new array to prevent from duplication of image display by changing value in the array from '0' to '1' so next time can avoid display '1' marked image.
I succeeded initial setting all arrays with NSInteger 0, with replaceObjectAtIndex:withObject: method in a 'ViewDidLaod' method, however, I have an error when I want to change the value into '1' in the array with replaceObjectAtIndex:withObject:, the same method I used in the 'ViewDidLaod' method.
I already searched google and stack but people who got the same problem used immutable array, that's why they had an issue, but I have mutable array in my code. Please help me.
The error message is below:
2015-04-13 03:55:25.824 InfanTree[4474:166010] -[__NSCFNumber length]: unrecognized selector sent to instance 0xb000000000000002
2015-04-13 03:55:25.846 InfanTree[4474:166010] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber length]: unrecognized selector sent to instance 0xb000000000000002'
*** First throw call stack:
(
0 CoreFoundation 0x000000010826fa75 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x0000000107f08bb7 objc_exception_throw + 45
2 CoreFoundation 0x0000000108276d1d -[NSObject(NSObject) doesNotRecognizeSelector:] + 205
3 CoreFoundation 0x00000001081ce9dc ___forwarding___ + 988
4 CoreFoundation 0x00000001081ce578 _CF_forwarding_prep_0 + 120
5 UIKit 0x0000000108f13f06 +[_UIAssetManager createAssetNamed:fromBundle:] + 67
6 UIKit 0x00000001088d4f60 +[UIImage imageNamed:inBundle:compatibleWithTraitCollection:] + 221
7 InfanTree 0x00000001079c92d0 -[ViewController collectionView:cellForItemAtIndexPath:] + 512
8 UIKit 0x0000000108ed1fab -[UICollectionView _createPreparedCellForItemAtIndexPath:withLayoutAttributes:applyAttributes:] + 244
9 UIKit 0x0000000108ed36e4 -[UICollectionView _updateVisibleCellsNow:] + 3445
10 UIKit 0x0000000108ed7391 -[UICollectionView layoutSubviews] + 243
11 UIKit 0x000000010891c1c3 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 521
12 QuartzCore 0x000000010cc5ac58 -[CALayer layoutSublayers] + 150
13 QuartzCore 0x000000010cc4f87e _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 380
14 QuartzCore 0x000000010cc4f6ee _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24
15 QuartzCore 0x000000010cbbd36e _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 242
16 QuartzCore 0x000000010cbbe482 _ZN2CA11Transaction6commitEv + 390
17 UIKit 0x00000001088a068d -[UIApplication _reportMainSceneUpdateFinished:] + 44
18 UIKit 0x00000001088a1375 -[UIApplication _runWithMainScene:transitionContext:completion:] + 2684
19 UIKit 0x000000010889fd35 -[UIApplication workspaceDidEndTransaction:] + 179
20 FrontBoardServices 0x000000010bd92243 __31-[FBSSerialQueue performAsync:]_block_invoke + 16
21 CoreFoundation 0x00000001081a4c7c __CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 12
22 CoreFoundation 0x000000010819a9c5 __CFRunLoopDoBlocks + 341
23 CoreFoundation 0x000000010819a183 __CFRunLoopRun + 851
24 CoreFoundation 0x0000000108199bc6 CFRunLoopRunSpecific + 470
25 UIKit 0x000000010889f7a2 -[UIApplication _run] + 413
26 UIKit 0x00000001088a2580 UIApplicationMain + 1282
27 InfanTree 0x00000001079d19d3 main + 115
28 libdyld.dylib 0x000000010aa60145 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
Whole code is here
Below is part of my code.
#interface ViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>
{
DataModel *_data;
// save the indexPath value itself of the picture which is selected at specific index path
NSMutableArray *_displayedImageIndexPathHistory;
// save 1 for the first rendering so next time can avoid to be selected
NSMutableArray *_isSelectedBefore;
// save 1 if rendered at least once so can avoid duplication
NSMutableArray *_preventDuplication;
}
#end
#implementation ViewController
.
.
.
- (void)viewDidLoad {
[super viewDidLoad];
.
.
.
// _data.imageSet is a two dimensional 'MUTABLE' array which has 'MUTABLE' arrays in it.
// Declared in a Model class. Each element has NSString *imageName.png.
_preventDuplication = [_data.imageSet mutableCopy];
_displayedImageIndexPathHistory = [_data.imageSet mutableCopy];
_isSelectedBefore = [_data.imageSet mutableCopy];
// set all arrays with 0
NSInteger sectionNum = [_data.imageSet count];
NSNumber *defaultNumber = [NSNumber numberWithInt:0];
for (NSInteger i = 0; i < sectionNum; i++) {
for (NSInteger j = 0; j < [_data.imageSet[i] count]; j++) {
[_displayedImageIndexPathHistory[i] replaceObjectAtIndex:j withObject:defaultNumber];
[_isSelectedBefore[i] replaceObjectAtIndex:j withObject:defaultNumber];
[_preventDuplication[i] replaceObjectAtIndex:j withObject:defaultNumber];
}
}
.
.
.
}
.
.
.
-(UICollectionViewCell *) collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
CollectionViewCell *cell = [self.collectionView dequeueReusableCellWithReuseIdentifier:#"Cell" forIndexPath:indexPath];
NSNumber *defaultNumber = [NSNumber numberWithInt:0];
NSNumber *markingNumber = [NSNumber numberWithInt:1];
if (indexPath.row == 0) {
cell.cellImageView.image = [UIImage imageNamed:[_data.imageSet[indexPath.section] objectAtIndex:indexPath.row]];
// **Have error at this sentence!!**
[_preventDuplication[indexPath.section] replaceObjectAtIndex:indexPath.row withObject: markingNumber];
}
else {
.
.
.
}
.
.
return cell;
}
Thanks in advance.
Your code has the expression:
[UIImage imageNamed:[_data.imageSet[indexPath.section] objectAtIndex:indexPath.row]]
It would seem that this part:
[_data.imageSet[indexPath.section] objectAtIndex:indexPath.row]
Is producing an instance of NSNumber, not an instance of NSString. Of course, +[UIImage imageNamed:] requires its argument to be a string. It's apparently invoking -length on it. Since NSNumber doesn't respond to -length, you get that exception and crash.
Using Chat Application with XMPPFramework Iam getting This Error
Message SendButton Action as given below, plz help me if any one have idea then tell me plz..............
- (IBAction)sendAction:(id)sender
{
if([_chatTextField.text length] > 0)
{
NSString* po = getUser.ofUser;
bubbleTable.typingBubble = NSBubbleTypingTypeNobody;
NSBubbleData *messageBubble = [NSBubbleData dataWithText:_chatTextField.text date:[NSDate dateWithTimeIntervalSinceNow:0] type:BubbleTypeMine];
[bubbleData addObject:messageBubble];
[bubbleTable reloadData];
[bubbleTable scrollBubbleViewToBottomAnimated:YES];
[[QuoteMessageController SharedInstance] SendChatMessageTo:getUser.account withContent:_chatTextField.text toUserId:[NSString stringWithFormat:#"%ld", (long)getUser.Id] andOFId:po andVerifyKey:chatMessageKey];
}
Getting error in output as given bellow>>>>>>
*** First throw call stack:
(
0 CoreFoundation 0x000000010e18ff35 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x000000010da7bbb7 objc_exception_throw + 45
2 CoreFoundation 0x000000010e18fe6d +[NSException raise:format:] + 205
3 Foundation 0x000000010ba211f8 -[NSString stringByAppendingString:] + 96
4 SourceSage 0x000000010ae0c939 +[SSWriteReadInDb writeQuotesTable:UserImageUrl:UserId:OfUser:] + 409
5 SourceSage 0x000000010adb8d56 -[QuoteMessageController SendChatMessageTo:withContent:toUserId:andOFId:andVerifyKey:] + 2454
6 SourceSage 0x000000010ad6ac30 -[SSChatViewController sendAction:] + 752
7 UIKit 0x000000010beb48be -[UIApplication sendAction:to:from:forEvent:] + 75
8 UIKit 0x000000010bfbb410 -[UIControl _sendActionsForEvents:withEvent:] + 467
9 UIKit 0x000000010bfba7df -[UIControl touchesEnded:withEvent:] + 522
10 UIKit 0x000000010befa308 -[UIWindow _sendTouchesForEvent:] + 735
11 UIKit 0x000000010befac33 -[UIWindow sendEvent:] + 683
12 UIKit 0x000000010bec79b1 -[UIApplication sendEvent:] + 246
13 UIKit 0x000000010bed4a7d _UIApplicationHandleEventFromQueueEvent + 17370
14 UIKit 0x000000010beb0103 _UIApplicationHandleEventQueue + 1961
15 CoreFoundation 0x000000010e0c5551 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
16 CoreFoundation 0x000000010e0bb41d __CFRunLoopDoSources0 + 269
17 CoreFoundation 0x000000010e0baa54 __CFRunLoopRun + 868
18 CoreFoundation 0x000000010e0ba486 CFRunLoopRunSpecific + 470
19 GraphicsServices 0x000000010fe7c9f0 GSEventRunModal + 161
20 UIKit 0x000000010beb3420 UIApplicationMain + 1282
21 SourceSage 0x000000010ae02893 main + 115
22 libdyld.dylib 0x000000010ee2e145 start + 1
23 ??? 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
After looking at this part of your stack trace:
2 CoreFoundation 0x000000010e18fe6d +[NSException raise:format:] + 205
3 Foundation 0x000000010ba211f8 -[NSString stringByAppendingString:] + 96
4 SourceSage 0x000000010ae0c939 +[SSWriteReadInDb writeQuotesTable:UserImageUrl:UserId:OfUser:] + 409
5 SourceSage 0x000000010adb8d56 -[QuoteMessageController SendChatMessageTo:withContent:toUserId:andOFId:andVerifyKey:] + 2454
6 SourceSage 0x000000010ad6ac30 -[SSChatViewController sendAction:] + 752
You'll see the exception is raised after a string is appended to a string. That is usually caused from appending nil to the string. By guess is that one of your NSString arguments that you're sending to the method below is nil.
[[QuoteMessageController SharedInstance] SendChatMessageTo:getUser.account
withContent:_chatTextField.text
toUserId:[NSString stringWithFormat:#"%ld", (long)getUser.Id]
andOFId:po
andVerifyKey:chatMessageKey];
To find out if this is in fact the case, either set a breakpoint here and check all the values, or add in the following before you call this method:
NSLog(#"%#", getUser.account);
NSLog(#"%#", _chatTextField.text);
NSLog(#"%#", po);
NSLog(#"%#", [NSString stringWithFormat:#"%ld", (long)getUser.Id]);
NSLog(#"%#", chatMessageKey);
I don't know what your parameters actually are, so remove the NSLogs for the variables that are not NSString. If one of these logs come back as nil or null (I forget what the console will output), then you found your issue. If it's an argument that you don't necessarily need, you should pass an empty NSString instead. I usually do this with a ternary. So assuming the culprit is _chatTextField.text, I would pass that argument as:
[[QuoteMessageController SharedInstance] SendChatMessageTo:getUser.account
withContent:_chatTextField.text ?: #""
toUserId:[NSString stringWithFormat:#"%ld", (long)getUser.Id]
andOFId:po
andVerifyKey:chatMessageKey];
Doing this basically says, if _chatTextField.text is true (which it will equate to if it is not nill), use that value, otherwise use #""
EDIT:
- (IBAction)sendAction:(id)sender
{
if([_chatTextField.text length] > 0)
{
NSString* po = getUser.ofUser ?: #"";
NSString *acct = getUser.account ?: #"";
bubbleTable.typingBubble = NSBubbleTypingTypeNobody;
NSBubbleData *messageBubble = [NSBubbleData dataWithText:_chatTextField.text date:[NSDate dateWithTimeIntervalSinceNow:0] type:BubbleTypeMine];
[bubbleData addObject:messageBubble];
[bubbleTable reloadData];
[bubbleTable scrollBubbleViewToBottomAnimated:YES];
[[QuoteMessageController SharedInstance] SendChatMessageTo:acct withContent:_chatTextField.text toUserId:[NSString stringWithFormat:#"%ld", (long)getUser.Id] andOFId:po andVerifyKey:chatMessageKey];
}
I am going crazy trying to debug this. I am trying to basically duplicate a row in my SQLite db and increment a value. I have used similar insert statements elsewhere in my code and had no problems, but this time it is not cooperating. The program errors when it gets to the executeUpdate statement.
I am relatively new to iOS programming and have gone as far as I can on my own.
Here is my function:
+ (BOOL)updatePetWithNewVet:(NSNumber *)i {
NSString *appSupportDir = [NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES) lastObject];
NSString *dbPath = [appSupportDir stringByAppendingPathComponent:#"pets.sqlite"];
FMDatabase *database = [FMDatabase databaseWithPath:dbPath];
[database open];
FMResultSet *results = [database executeQuery:#"Select * from vets order by vetID desc limit 1"];
if ([results next]) {
NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
NSInteger vID = [results intForColumn:#"vetID"];
NSInteger vID2 = vID+1;
NSNumber *newVetID = [NSNumber numberWithInteger:vID2];
NSString *vName = [results stringForColumn:#"vetName"];
NSString *vPhone = [results stringForColumn:#"vetPhone"];
NSString *vStreet = [results stringForColumn:#"vetStreet"];
NSString *vCity = [results stringForColumn:#"vetCity"];
NSString *vState = [results stringForColumn:#"vetState"];
NSNumber *vZipcode = [f numberFromString:[results stringForColumn:#"vetZipcode"]];
NSLog(#"%#", vName);
NSLog(#"%#", vPhone);
NSLog(#"%#", vStreet);
NSLog(#"%#", vCity);
NSLog(#"%#", vState);
NSLog(#"%#", vZipcode);
NSLog(#"VET ID: %ld", (long)vID);
NSLog(#"NEW VET ID: %#", newVetID);
[results close];
[database executeUpdateWithFormat:#"INSERT INTO vets (vetID, vetName, vetPhone, vetStreet, vetCity, vetState, vetZipcode) Values (?, ?, ?, ?, ?, ?, ?)", newVetID, vName, vPhone, vStreet, vCity, vState, vZipcode, nil];
NSLog(#"%#", [database lastErrorMessage]);
}
[database close];
return 1;
}
And it is not working. This is what get when I crash:
2014-11-29 09:35:54.722 PetJournal[58823:8400345] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array'
*** First throw call stack:
(
0 CoreFoundation 0x000000010eb37f35 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x000000010e7d0bb7 objc_exception_throw + 45
2 CoreFoundation 0x000000010ea22f33 -[__NSArrayM objectAtIndex:] + 227
3 PetJournal 0x000000010cc1744e -[FMDatabase executeUpdate:error:withArgumentsInArray:orDictionary:orVAList:] + 2542
4 PetJournal 0x000000010cc17fa8 -[FMDatabase executeUpdate:withArgumentsInArray:] + 152
5 PetJournal 0x000000010cc1834d -[FMDatabase executeUpdateWithFormat:] + 637
6 PetJournal 0x000000010cc54fd7 +[UIView(Database) updatePetWithNewVet:] + 1159
7 PetJournal 0x000000010cc549d2 +[UIView(Database) createPetNamed:withBirthday:] + 1522
8 PetJournal 0x000000010cc3165e -[AddPetViewController savePet:] + 398
9 UIKit 0x000000010d07a8be -[UIApplication sendAction:to:from:forEvent:] + 75
10 UIKit 0x000000010d181410 -[UIControl _sendActionsForEvents:withEvent:] + 467
11 UIKit 0x000000010d1807df -[UIControl touchesEnded:withEvent:] + 522
12 UIKit 0x000000010d0c0308 -[UIWindow _sendTouchesForEvent:] + 735
13 UIKit 0x000000010d0c0c33 -[UIWindow sendEvent:] + 683
14 UIKit 0x000000010d08d9b1 -[UIApplication sendEvent:] + 246
15 UIKit 0x000000010d09aa7d _UIApplicationHandleEventFromQueueEvent + 17370
16 UIKit 0x000000010d076103 _UIApplicationHandleEventQueue + 1961
17 CoreFoundation 0x000000010ea6d551 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
18 CoreFoundation 0x000000010ea6341d __CFRunLoopDoSources0 + 269
19 CoreFoundation 0x000000010ea62a54 __CFRunLoopRun + 868
20 CoreFoundation 0x000000010ea62486 CFRunLoopRunSpecific + 470
21 GraphicsServices 0x00000001114139f0 GSEventRunModal + 161
22 UIKit 0x000000010d079420 UIApplicationMain + 1282
23 PetJournal 0x000000010cc33f63 main + 115
24 libdyld.dylib 0x000000010f2d2145 start + 1
25 ??? 0x0000000000000001 0x0 + 1
)
You are using executeUpdateWithFormat, but are not using printf-style syntax in your SQL. Either use executeUpdateWithFormat with printf-style format string, or use executeUpdate with the ? placeholders.
Personally, I'd suggest you just use executeUpdate (and drop the nil from the end of the list).
My app is working great, the only issue i have right now it's with the live data viewer, if nothing is happening the XML file is empty, and the app displays nothing to show right now, if it has 2 or 2000 events happening, it displays in my live data viewer, if there is only a single event occurring my app crashes when i got to that view.
I have compared the XML structures and they are the same for 1 or 2+ events.
I have included below my XML parser method, my cellForRowAtIndexPath and my numberOfRows method.
Is there anyone out there that can see what's the issue? I remind you again, this only crashes if my XML file has a single Match node. Works fine with 0 or 100000 but not with 1.
At the end you will also find the crash report, i hope it's useful in finding the problem and fixing it.
Thank you.
-(void) parseXMLLiveMatch
{
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"something.xml"]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *xmlString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSDictionary *xml = [NSDictionary dictionaryWithXMLString:xmlString];
NSMutableArray *items = [xml objectForKey:#"Match"];
NSMutableArray *newLiveMatchArray = [[NSMutableArray alloc] init];
for (NSDictionary *dict in items) {
NSLog(#"%# %#", [dict class], dict);
LiveMatchObject *myMatches = [LiveMatchObject matchesFromXMLDictionary:dict];
[newLiveMatchArray addObject:myMatches];
}
NSNull *nullValue = [NSNull null];
[newLiveMatchArray insertObject:nullValue atIndex:0];
[self setTableDataLiveMatch:newLiveMatchArray];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"LiveIdent";
LiveViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
LiveMatchObject *item = [tableDataLiveMatch objectAtIndex:(int)([indexPath row]/2)];
...
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return tableDataLiveMatch.count * 2;
}
2014-02-17 14:40:56.419 Liga Zon Sagres Companion[2539:70b] __NSCFString HomeGoals
2014-02-17 14:40:56.420 Liga Zon Sagres Companion[2539:70b] -[__NSCFString objectForKeyedSubscript:]: unrecognized selector sent to instance 0x10d03d7f0
2014-02-17 14:40:56.424 Liga Zon Sagres Companion[2539:70b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString objectForKeyedSubscript:]: unrecognized selector sent to instance 0x10d03d7f0'
*** First throw call stack:
(
0 CoreFoundation 0x00000001019df795 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x0000000101742991 objc_exception_throw + 43
2 CoreFoundation 0x0000000101a70bad -[NSObject(NSObject) doesNotRecognizeSelector:] + 205
3 CoreFoundation 0x00000001019d109d ___forwarding___ + 973
4 CoreFoundation 0x00000001019d0c48 _CF_forwarding_prep_0 + 120
5 Liga Zon Sagres Companion 0x00000001000014da +[LiveMatchObject matchesFromXMLDictionary:] + 138
6 Liga Zon Sagres Companion 0x0000000100003da6 -[LiveTableViewController parseXMLLiveMatch] + 790
7 Liga Zon Sagres Companion 0x0000000100003a48 -[LiveTableViewController viewWillAppear:] + 88
8 UIKit 0x00000001004943f4 -[UIViewController _setViewAppearState:isAnimating:] + 394
9 UIKit 0x00000001004c0ce5 -[UITabBarController transitionFromViewController:toViewController:transition:shouldSetSelected:] + 524
10 UIKit 0x00000001004bd155 -[UITabBarController _setSelectedViewController:] + 259
11 UIKit 0x00000001004c046c -[UITabBarController _tabBarItemClicked:] + 248
12 UIKit 0x00000001003a6096 -[UIApplication sendAction:to:from:forEvent:] + 80
13 UIKit 0x00000001003a6044 -[UIApplication sendAction:toTarget:fromSender:forEvent:] + 17
14 UIKit 0x00000001005fb4cc -[UITabBar _sendAction:withEvent:] + 420
15 UIKit 0x00000001003a60ae -[UIApplication sendAction:to:from:forEvent:] + 104
16 UIKit 0x00000001003a6044 -[UIApplication sendAction:toTarget:fromSender:forEvent:] + 17
17 UIKit 0x000000010047a450 -[UIControl _sendActionsForEvents:withEvent:] + 203
18 UIKit 0x00000001003a6096 -[UIApplication sendAction:to:from:forEvent:] + 80
19 UIKit 0x00000001003a6044 -[UIApplication sendAction:toTarget:fromSender:forEvent:] + 17
20 UIKit 0x000000010047a450 -[UIControl _sendActionsForEvents:withEvent:] + 203
21 UIKit 0x00000001004799c0 -[UIControl touchesEnded:withEvent:] + 530
22 UIKit 0x00000001003dac15 -[UIWindow _sendTouchesForEvent:] + 701
23 UIKit 0x00000001003db633 -[UIWindow sendEvent:] + 988
24 UIKit 0x00000001003b4fa2 -[UIApplication sendEvent:] + 211
25 UIKit 0x00000001003a2d7f _UIApplicationHandleEventQueue + 9549
26 CoreFoundation 0x000000010196eec1 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
27 CoreFoundation 0x000000010196e792 __CFRunLoopDoSources0 + 242
28 CoreFoundation 0x000000010198a61f __CFRunLoopRun + 767
29 CoreFoundation 0x0000000101989f33 CFRunLoopRunSpecific + 467
30 GraphicsServices 0x000000010300b3a0 GSEventRunModal + 161
31 UIKit 0x00000001003a5043 UIApplicationMain + 1010
32 Liga Zon Sagres Companion 0x000000010001fce3 main + 115
33 libdyld.dylib 0x000000010232b5fd start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
Cheers and thank you.
As resquested:
#implementation LiveMatchObject
#synthesize homeGoals, awayGoals, homeName, awayName, matchDate, matchMinute, matchStatus, homeTeamLogo, awayTeamLogo, spectators, round, homeStartingGoalie, homeStartingDefense, homeStartingMiddlefield, homeStartingFoward, homeFormation, awayStartingGoalie, awayStartingDefense, awayStartingMiddlefield, awayStartingFoward, awayFormation;
+(LiveMatchObject *)matchesFromXMLDictionary:(NSDictionary *)dict{
LiveMatchObject *object =[[LiveMatchObject alloc]init];
object.homeGoals = dict[#"HomeGoals"];
object.awayGoals = dict[#"AwayGoals"];
object.homeName = dict[#"Hometeam"];
object.awayName = dict[#"Awayteam"];
object.matchDate = dict[#"Date"];
object.matchMinute = dict[#"Time"];
object.matchStatus = [UIImage imageNamed:dict[#"Time"]];
object.homeTeamLogo = [UIImage imageNamed:dict[#"HomeTeam_Id"]];
object.awayTeamLogo = [UIImage imageNamed:dict[#"AwayTeam_Id"]];
object.spectators = dict[#"Spectators"];
object.round = dict[#"Round"];
object.homeFormation = dict[#"HomeTeamFormation"];
object.homeStartingGoalie = dict[#"HomeLineupGoalkeeper"];
object.homeStartingMiddlefield = dict[#"HomeLineupMidfield"];
object.homeStartingFoward = dict[#"HomeLineupForward"];
object.awayFormation = dict[#"AwayTeamFormation"];
object.awayStartingGoalie = dict[#"AwayLineupGoalkeeper"];
object.awayStartingMiddlefield = dict[#"AwayLineupMidfield"];
object.awayStartingFoward = dict[#"AwayLineupForward"];
return object;
}
#end
The XML
<CREPERR.COM >
<Match>
<Id>327080</Id>
<Date>2014-02-17T12:00:00-08:00</Date>
<League>Primeira Liga</League>
<Round>19</Round>
<Spectators/>
<Hometeam>Estoril-Praia</Hometeam>
<HomeTeam_Id>529</HomeTeam_Id>
<Awayteam>Braga</Awayteam>
<AwayTeam_Id>521</AwayTeam_Id>
<Time>9'</Time>
<HomeGoals>0</HomeGoals>
<AwayGoals>0</AwayGoals>
<HomeGoalDetails/>
<AwayGoalDetails/>
<HomeLineupGoalkeeper>Vagner</HomeLineupGoalkeeper>
<AwayLineupGoalkeeper>Eduardo</AwayLineupGoalkeeper>
<HomeLineupDefense>Yohan Tavares; Mano; Babanco; Ruben;</HomeLineupDefense>
<AwayLineupDefense>
Nurio; Aleksandar Miljkovic; Nuno André Coelho; Vincent Sasso;
</AwayLineupDefense>
<HomeLineupMidfield>
Javier Balboa; Goebel Evandro; Carlitos; Diogo Amado; Goncalo;
</HomeLineupMidfield>
<AwayLineupMidfield>
Custodio; Mauro; Leandro Kappel; Felipe Pardo; Alan;
</AwayLineupMidfield>
<HomeLineupForward>Seba;</HomeLineupForward>
<AwayLineupForward>Raul Andrei Rusescu;</AwayLineupForward>
<HomeSubDetails/>
<AwaySubDetails/>
<HomeTeamFormation>4-2-3-1</HomeTeamFormation>
<AwayTeamFormation>4-2-3-1</AwayTeamFormation>
<Location>Estádio António Coimbra da Mota</Location>
<Stadium>Estádio António Coimbra da Mota</Stadium>
<HomeTeamYellowCardDetails/>
<AwayTeamYellowCardDetails/>
<HomeTeamRedCardDetails/>
<AwayTeamRedCardDetails/>
</Match>
<AccountInformation>
Data requested at 2/17/2014
</AccountInformation>
</CREPERR.COM>
You are crashing because when there is only one object in your array the dict object is an NSString, not an NSDictionary. NSString does not respond the the string[#"Something"] interface, and therefore is crashing your application.
One way to test for this is:
+(LiveMatchObject *)matchesFromXMLDictionary:(NSDictionary *)dict{
if([dict isKindOfClass:[NSDictionary class]])
{
//This is a valid dictionary
}
else
{
//This is not a dictionary object, do something different
}
}
Why you are getting an NSString here instead of an NSDictionary I have no idea, and how you deal with it to get your data out in the same fashion is another question. You are going to have to set a breakpoint in there and see what NSString you are getting and what to do with it.