I am trying to append the string of a Retweeted tweet in Objective-C however I am always getting an issue with certain types of tweets. I believe that there is something wrong in the way I am attempting to substring the tweets. My code is shown below
2015-08-20 15:40:20.699 Floadt[21417:932559] *** Terminating app due to uncaught exception 'NSRangeException', reason: '-[__NSCFString substringWithRange:]: Range {9223372036854775807, 52} out of bounds; string length 70'
*** First throw call stack:
(
0 CoreFoundation 0x000000010cd58c65 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x000000010c631bb7 objc_exception_throw + 45
2 CoreFoundation 0x000000010cd58b9d +[NSException raise:format:] + 205
3 CoreFoundation 0x000000010cc7fb98 -[__NSCFString substringWithRange:] + 136
4 Floadt 0x000000010929efa4 -[TwitterTableViewController tableView:cellForRowAtIndexPath:] + 2260
5 UIKit 0x000000010b465a28 -[UITableView _createPreparedCellForGlobalRow:withIndexPath:willDisplay:] + 508
6 UIKit 0x000000010b444248 -[UITableView _updateVisibleCellsNow:isRecursive:] + 2853
7 UIKit 0x000000010b45a8a9 -[UITableView layoutSubviews] + 210
8 UIKit 0x000000010b3e4a2b -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 536
9 QuartzCore 0x000000010b1a6ec2 -[CALayer layoutSublayers] + 146
10 QuartzCore 0x000000010b19b6d6 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 380
11 QuartzCore 0x000000010b19b546 _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24
12 QuartzCore 0x000000010b107886 _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 242
13 QuartzCore 0x000000010b108a3a _ZN2CA11Transaction6commitEv + 462
14 QuartzCore 0x000000010b1090eb _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 89
15 CoreFoundation 0x000000010cc8bca7 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 23
16 CoreFoundation 0x000000010cc8bc00 __CFRunLoopDoObservers + 368
17 CoreFoundation 0x000000010cc81a33 __CFRunLoopRun + 1123
18 CoreFoundation 0x000000010cc81366 CFRunLoopRunSpecific + 470
19 GraphicsServices 0x000000010eb09a3e GSEventRunModal + 161
20 UIKit 0x000000010b364900 UIApplicationMain + 1282
21 Floadt 0x000000010936574f main + 111
22 libdyld.dylib 0x000000010f32f145 start + 1
23 ??? 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
Here is my code to Append the string:
if ([self Contains:#"RT" on:[data objectForKey:#"text"]]) {
TwitterRetweetCell *cell = [self.tableView dequeueReusableCellWithIdentifier:#"TwitterRetweetCell"];
cell.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"Background.png"]];
if (cell == nil) {
cell = [[TwitterRetweetCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"TwitterRetweetCell"];
}
// Lookup RT User
NSString *text = [data objectForKey:#"text"];
NSRange start = [text rangeOfString:#"RT #"];
NSRange end = [text rangeOfString:#":"];
NSString *shortString = [text substringWithRange:NSMakeRange(start.location, end.location)];
NSString *evenShorterString = [shortString substringFromIndex:4];
[self lookupTwitterUser:evenShorterString];
//Set username for twitter
[cell.nameLabel setText:evenShorterString];
//Set Retweet Status
NSString *retName = [NSString stringWithFormat:#"Retweeted by %#",data[#"user"][#"screen_name"]];
[cell.retweetedLabel setText:retName];
//Set Profile Pic for Twitter
return cell;
}
The two ranges:
NSRange start = [text rangeOfString:#"RT #"];
NSRange end = [text rangeOfString:#":"];
You need to check that those substrings were actually found and only use the ranges if they were found. Otherwise the rest of your code will fail because the range's location will be NSNotFound, which is the large number in your crash log. That suggests that your code encountered text containing "RT" but not "RT #". You should perform the following check before attempting to use start and end:
if (start.location != NSNotFound && end.location != NSNotFound)
{
// use start and end
}
Or better still, use this if condition instead of if ([self Contains:#"RT" on:[data objectForKey:#"text"]]).
Related
[__NSDictionaryM safeObjectAtIndex:]: unrecognized selector sent to instance 0x60800005e060
[__NSDictionaryM safeObjectAtIndex:]: unrecognized selector sent to instance 0x60800005e060 [IssuesViewController-tableView:cellForRowAtIndexPath:]
Assertion failure in -[STCollapseTableView _configureCellForDisplay:forIndexPath:], /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit_Sim/UIKit-3600.7.47/UITableView.m:8174
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UITableView (; layer = ; contentOffset: {0, 0}; contentSize: {414, 115}>) failed to obtain a cell from its dataSource (; layer = ; contentOffset: {0, 0}; contentSize: {414, 115}>)'
*** First throw call stack:
(
0 CoreFoundation 0x0000000108d8bb0b __exceptionPreprocess + 171
1 libobjc.A.dylib 0x00000001087c3141 objc_exception_throw + 48
2 CoreFoundation 0x0000000108d8fcf2 +[NSException raise:format:arguments:] + 98
3 Foundation 0x000000010835d3b6 -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 193
4 UIKit 0x0000000109aeefcf -[UITableView _configureCellForDisplay:forIndexPath:] + 230
5 UIKit 0x0000000109afa7b8 -[UITableView _createPreparedCellForGlobalRow:withIndexPath:willDisplay:] + 836
6 UIKit 0x0000000109afa9a8 -[UITableView _createPreparedCellForGlobalRow:willDisplay:] + 74
7 UIKit 0x0000000109acf2e9 -[UITableView _updateVisibleCellsNow:isRecursive:] + 2845
8 UIKit 0x0000000109b0397c -[UITableView _performWithCachedTraitCollection:] + 111
9 UIKit 0x0000000109aeab2a -[UITableView layoutSubviews] + 233
10 UIKit 0x0000000109a5120b -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 1268
11 QuartzCore 0x0000000107905904 -[CALayer layoutSublayers] + 146
12 QuartzCore 0x00000001078f9526 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 370
13 QuartzCore 0x00000001078f93a0 _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24
14 QuartzCore 0x0000000107888e92 _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 294
15 QuartzCore 0x00000001078b5130 _ZN2CA11Transaction6commitEv + 468
16 UIKit 0x0000000109987307 _UIApplicationFlushRunLoopCATransactionIfTooLate + 167
17 UIKit 0x000000010a187cab __handleEventQueue + 5843
18 CoreFoundation 0x0000000108d31c01 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
19 CoreFoundation 0x0000000108d170cf __CFRunLoopDoSources0 + 527
20 CoreFoundation 0x0000000108d165ff __CFRunLoopRun + 911
21 CoreFoundation 0x0000000108d16016 CFRunLoopRunSpecific + 406
22 GraphicsServices 0x000000010b8eaa24 GSEventRunModal + 62
23 UIKit 0x000000010998e0d4 UIApplicationMain + 159
24 comress 0x000000010626910f main + 111
25 libdyld.dylib 0x000000010b4d765d start + 1)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
This is sample code:
NSArray *postDupe = [[_postsArray valueForKeyPath:#"#unionOfArrays.#allValues"] valueForKeyPath:#"post"];
NSArray *foundArray = nil;
predicate = [NSPredicate predicateWithFormat:#"post_id.stringValue contains [c] %#",#"18586"];
foundArray = [postDupe filteredArrayUsingPredicate:predicate];
long foundIndex = 0;
long count = 0;
for (int i=0; i<foundArray.count; i++)
{
foundIndex = [postDupe indexOfObject: [foundArray objectAtIndex: i]];
//NSLog(#"%# is at index %d", string, index);
}
_filterPostsArray = [_postsArray objectAtIndex:foundIndex];
}
searchActive = YES;
dispatch_async(dispatch_get_main_queue(),^{
[_issuesTable reloadData];
});
Sample Json Data:
<__NSArrayM 0x608000449a80>(
{
14556 = {
newCommentsCount = 0;
post = {
"post_id" = 18609;
seen = 1;
status = 0;
statusWasUpdated = 0;
"updated_on" = "1506061049.023";
};
};
},
)
[__NSDictionaryM safeObjectAtIndex:]: unrecognized selector sent to instance
Looks like you have a dictionary and are treating it like an array.
Run your code in the debugger and examine the values of the variables as you move through your algorithm, this should show you where you go wrong.
Guessing:
The key path in your predicate post_id.stringValue should be post.post_id.stringValue - your dictionary contains a key post whose value is itself a dictionary which has a key post_id.
_filterPostsArray = [_postsArray objectAtIndex:foundIndex] sounds like it is assigning a dictionary to an array. You probably wanted this statement to be in the loop and adding the dictionary as a new element to the array?
HTH
I have a tableView which should load its cells with data from server.
When my data is loaded from server I call [self.tableView reloadData] inside completionhandler block.
So the method cellForRowAtIndexPath gets called again.
My implementation for cellForRowAtIndexPath is this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// Configure the cell...
NewsCell* cell = [self.tableView dequeueReusableCellWithIdentifier:#"NewsCell" forIndexPath:indexPath];
if(!cell){
cell = [[NewsCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"NewsCell"];
}
News* currentNews = (News*)[self.newsList objectAtIndex:indexPath.row];
cell.newsTitle.text = currentNews.title;
// cell.newsTitle.text = #"salam";
return cell;
}
Note: self.newsList is an array that is populated with data from server
The code that parses response json from server is this:
[GNetworkHelper getJsonDataFromURL:urlString
withCompletionHandler:^(NSDictionary * jsonResponse) {
// Parse retrieved json and pass it to completion handler;;
NSMutableArray* news = [[NSMutableArray alloc] init];
if (jsonResponse) {
for (NSDictionary* new in jsonResponse) {
News *currentNew = [[News alloc] initWithDictionary:new];
[news addObject:currentNew];
}
}else{
News* testNew = [[News alloc] init];
[testNew setTitle:#"salam"];
[news addObject:testNew];
}
completionHandler(news);
}];
My problem: When I debug this code the cell variable I create using dequeueReusableCellWithIdentifier:forIndexPath function is null in the debugger's variables section, but when I use lldb command po to print it out I get this
(lldb) po cell
<NewsCell: 0x7fc5fadb2ee0; baseClass = UITableViewCell; frame = (0 0; 375 143); autoresize = W; layer = <CALayer: 0x7fc5fad9fcd0>>
The same happens for currentNews variable. For it I get this from po command
(lldb) po currentNews
<News: 0x7fc5fd0480d0>
I even can get properties on it like this:
(lldb) po currentNews.title
<__NSCFArray 0x7fc5fd047300>(
"some title"
)
There is no exception when stepping through this method's statements. But when the method returns the Unrecognized Selector exception is thrown
Why this happens??
The Strange thing is that if I change this line:
cell.newsTitle.text = currentNews.title;
to this:
cell.newsTitle.text = #"Some test text";
everything goes well, specifically the cell and currentNews variables are not null anymore and tableView renders the cells without any problem
The full stack trace is :
[__NSCFArray length]: unrecognized selector sent to instance 0x7fc5fd047300
2015-09-16 11:30:40.630 Gallery[12013:952548] Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFArray length]: unrecognized selector sent to instance 0x7fc5fd047300'
--- First throw call stack:
(
0 CoreFoundation 0x0000000105af3f35 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x000000010578cbb7 objc_exception_throw + 45
2 CoreFoundation 0x0000000105afb04d -[NSObject(NSObject) doesNotRecognizeSelector:] + 205
3 CoreFoundation 0x0000000105a5327c ___forwarding___ + 988
4 CoreFoundation 0x0000000105a52e18 _CF_forwarding_prep_0 + 120
5 UIKit 0x00000001060a5f45 -[UILabel _textRectForBounds:limitedToNumberOfLines:includingShadow:] + 65
6 UIKit 0x00000001060a5da0 -[UILabel textRectForBounds:limitedToNumberOfLines:] + 76
7 UIKit 0x00000001060a9852 -[UILabel _intrinsicSizeWithinSize:] + 170
8 UIKit 0x00000001060a9932 -[UILabel intrinsicContentSize] + 76
9 UIKit 0x000000010655fea4 -[UIView(UIConstraintBasedLayout) _generateContentSizeConstraints] + 33
10 UIKit 0x000000010655fc64 -[UIView(UIConstraintBasedLayout) _updateContentSizeConstraints] + 422
11 UIKit 0x00000001065670d6 -[UIView(AdditionalLayoutSupport) updateConstraints] + 163
12 UIKit 0x00000001060a979d -[UILabel updateConstraints] + 272
13 UIKit 0x00000001065666fa -[UIView(AdditionalLayoutSupport) _internalUpdateConstraintsIfNeededAccumulatingViewsNeedingSecondPassAndViewsNeedingBaselineUpdate:] + 248
14 UIKit 0x00000001065668f2 -[UIView(AdditionalLayoutSupport) _updateConstraintsIfNeededAccumulatingViewsNeedingSecondPassAndViewsNeedingBaselineUpdate:] + 124
15 CoreFoundation 0x00000001059fc194 CFArrayApplyFunction + 68
16 UIKit 0x000000010656669b -[UIView(AdditionalLayoutSupport) _internalUpdateConstraintsIfNeededAccumulatingViewsNeedingSecondPassAndViewsNeedingBaselineUpdate:] + 153
17 Foundation 0x0000000105332d6e -[NSISEngine withBehaviors:performModifications:] + 155
18 UIKit 0x00000001065668f2 -[UIView(AdditionalLayoutSupport) _updateConstraintsIfNeededAccumulatingViewsNeedingSecondPassAndViewsNeedingBaselineUpdate:] + 124
19 CoreFoundation 0x00000001059fc194 CFArrayApplyFunction + 68
20 UIKit 0x000000010656669b -[UIView(AdditionalLayoutSupport) _internalUpdateConstraintsIfNeededAccumulatingViewsNeedingSecondPassAndViewsNeedingBaselineUpdate:] + 153
21 UIKit 0x00000001065668f2 -[UIView(AdditionalLayoutSupport) _updateConstraintsIfNeededAccumulatingViewsNeedingSecondPassAndViewsNeedingBaselineUpdate:] + 124
22 UIKit 0x0000000106566dbe __60-[UIView(AdditionalLayoutSupport) updateConstraintsIfNeeded]_block_invoke + 96
23 UIKit 0x0000000106566a86 -[UIView(AdditionalLayoutSupport) updateConstraintsIfNeeded] + 231
24 UIKit 0x000000010635c8b8 -[UITableViewCellContentView updateConstraintsIfNeeded] + 95
25 UIKit 0x000000010656719e -[UIView(AdditionalLayoutSupport) _updateConstraintsAtEngineLevelIfNeeded] + 159
26 UIKit 0x0000000105f4db2d -[UIView(Hierarchy) _updateConstraintsAsNecessaryAndApplyLayoutFromEngine] + 114
27 UIKit 0x0000000105f59973 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 521
28 QuartzCore 0x000000010504ade8 -[CALayer layoutSublayers] + 150
29 QuartzCore 0x000000010503fa0e _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 380
30 QuartzCore 0x000000010503f87e _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24
31 QuartzCore 0x0000000104fad63e _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 242
32 QuartzCore 0x0000000104fae74a _ZN2CA11Transaction6commitEv + 390
33 QuartzCore 0x0000000104faedb5 _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 89
34 CoreFoundation 0x0000000105a28dc7 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 23
35 CoreFoundation 0x0000000105a28d20 __CFRunLoopDoObservers + 368
36 CoreFoundation 0x0000000105a1eb53 __CFRunLoopRun + 1123
37 CoreFoundation 0x0000000105a1e486 CFRunLoopRunSpecific + 470
38 GraphicsServices 0x00000001085d29f0 GSEventRunModal + 161
39 UIKit 0x0000000105ee0420 UIApplicationMain + 1282
40 Gallery 0x000000010346ded3 main + 115
41 libdyld.dylib 0x0000000107325145 start + 1
42 ??? 0x0000000000000001 0x0 + 1
)
Can anybody tell me the reason for this?
The server JSON is an array of a string, ["some title"], and you expect it to be just a string "some title".
Try adding an assertion so that your parsing of the server data is correct.
News* currentNews = (News*)[self.newsList objectAtIndex:indexPath.row];
NSAssert([currentNews.title isKindOfClass:[NSString class]],
#"Title is not a string but a %#.",
NSStringFromClass([currentNews.title class]));
cell.newsTitle.text = currentNews.title;
It simply indicates at some point when you try to access title value in currentNews object, it would be null. thats why your app throws exception. put a condition to check null value.
Use following method to check any value/object exist or not.
Usage
write following code in your cellForRowAtIndexPath method.
if([self isEmpty:currentNews.title])
{
cell.newsTitle.text = #"default value";
}
else
{
cell.newsTitle.text = currentNews.title[0];
}
// Method to check empty value/object
- (BOOL)isEmpty:(id)object
{
return object == nil
|| [object isKindOfClass:[NSNull class]]
|| ([object respondsToSelector:#selector(length)]
&& [(NSData *)object length] == 0)
|| ([object respondsToSelector:#selector(count)]
&& [(NSArray *)object count] == 0);
}
Need your insight here...
This keeps crashing. Im calling a table on certain site, some say its the site that is causing but I can also make an exception. Can I get your two cents here?
NSRange blockStartRange = [pageContent rangeOfString:#"\t<table border=\"0\" cellpadding=\"4\" cellspacing=\"0\" id=\"table"];
NSRange blockEndRange = [pageContent rangeOfString:#"\t</table>" options:NSBackwardsSearch range:NSMakeRange(blockStartRange.location, [pageContent length] - blockStartRange.location)];
[HTMLString appendString:[pageContent substringWithRange:NSMakeRange(blockStartRange.location, blockEndRange.location + blockEndRange.length - blockStartRange.location)]];
// [HTMLString replaceOccurrencesOfString:#"width: 700px;" withString:#"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [HTMLString length])];
}
[webView loadHTMLString:HTMLString baseURL:[NSURL URLWithString:#"http://bowlatrabs.com/"]];
}
Error Log
2014-08-01 15:52:22.092 Bowl at Rabs[61401:90b] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSCFString rangeOfString:options:range:locale:]: Range {2147483647, 2147542871} out of bounds; string length 59222'
*** First throw call stack:
(
0 CoreFoundation 0x0270b1e4 __exceptionPreprocess + 180
1 libobjc.A.dylib 0x020178e5 objc_exception_throw + 44
2 CoreFoundation 0x0270afbb +[NSException raise:format:] + 139
3 Foundation 0x000c38cd -[NSString rangeOfString:options:range:locale:] + 185
4 Foundation 0x000cf156 -[NSString rangeOfString:options:range:] + 69
5 Bowl at Rabs 0x0002d9e8 -[LeagueController viewDidLoad] + 920
6 UIKit 0x005dc33d -[UIViewController loadViewIfRequired] + 696
7 UIKit 0x005dc5d9 -[UIViewController view] + 35
8 UIKit 0x005f6942 -[UINavigationController _startCustomTransition:] + 778
9 UIKit 0x006038f7 -[UINavigationController _startDeferredTransitionIfNeeded:] + 688
10 UIKit 0x006044e9 -[UINavigationController __viewWillLayoutSubviews] + 57
11 UIKit 0x007450d1 -[UILayoutContainerView layoutSubviews] + 213
12 UIKit 0x0052c964 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 355
13 libobjc.A.dylib 0x0202982b -[NSObject performSelector:withObject:] + 70
14 QuartzCore 0x04d9b45a -[CALayer layoutSublayers] + 148
15 QuartzCore 0x04d8f244 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 380
16 QuartzCore 0x04d8f0b0 _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 26
17 QuartzCore 0x04cf57fa _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 294
18 QuartzCore 0x04cf6b85 _ZN2CA11Transaction6commitEv + 393
19 QuartzCore 0x04cf7258 _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 92
20 CoreFoundation 0x026d336e __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 30
21 CoreFoundation 0x026d32bf __CFRunLoopDoObservers + 399
22 CoreFoundation 0x026b1254 __CFRunLoopRun + 1076
23 CoreFoundation 0x026b09d3 CFRunLoopRunSpecific + 467
24 CoreFoundation 0x026b07eb CFRunLoopRunInMode + 123
25 GraphicsServices 0x035765ee GSEventRunModal + 192
26 GraphicsServices 0x0357642b GSEventRun + 104
27 UIKit 0x004bdf9b UIApplicationMain + 1225
28 Bowl at Rabs 0x0000239c main + 76
29 libdyld.dylib 0x0325d725 start + 0
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
You need to handle the case where the strings do not exist. Apple's documentation for the rangeOfString: method says: "Returns {NSNotFound, 0} if aString is not found or is empty (#"")."
So you need to check to see if the returned ranges have range.location == NSNotFound and handle that in whatever way is best.
Other way to check is using NSRangeFromString
NSRangeFromString: Returns a range from a textual representation.
If the string passed into NSRangeFromString does not represent a valid range, it will return a range with its location and length set to 0.
NSString *string = #"invalid";
NSRange range = NSRangeFromString(string);
// {.location=0, .length=0}
You might check nshipster/range
I have a NSDictionary that I add to a mutable array but when I try add the array to populate a uitableview I get an error.
NSMutableArray *array = [[NSMutableArray alloc] init];
for (id element in self.categoriesMutableNameArray) {
[array addObject:#"No"];
}
self.categoryDict = #{ #"title" : self.categoriesMutableNameArray, #"selected" : array};
self.categoryArr = [[NSMutableArray alloc] init];
self.categoryMutableDict = [NSMutableDictionary dictionaryWithDictionary:self.categoryDict];
[self.categoryArr addObject:self.categoryDict];
and the following categoryArr is printed like this:
2014-02-27 15:09:07.397 App[7982:70b] (
{
selected = (
No,
No,
No,
No,
No,
No,
No,
No,
No,
No,
No,
No,
No,
No
);
title = (
"Fashion - Women",
"Fashion - Men",
Kids,
"Accessories - Women",
"Accessories - Men",
"Styling / Hair",
Inspiration,
"Decoration / Architecture",
"Great Places",
"Art / Design",
"Music / Movie / Books",
"Food / Drink",
"Gadgets / Tech",
Rides
);
}
)
The trouble I am having is in the uitableview cellforrowatindexpath method I try and add the title key for the categoryArr to populate the uitableview and I get the following error on this line:
UILabel *categoryLabel = (UILabel *)[cell viewWithTag:111];
categoryLabel.text = [NSString stringWithFormat:#"%#",[[self.categoryArr objectAtIndex:indexPath.row] objectForKey:#"title"];
And the error log:
2014-02-27 15:24:33.804 App[8153:70b] -[__NSArrayM length]: unrecognized selector sent to instance 0xa9bc3a0
2014-02-27 15:24:33.807 App[8153:70b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayM length]: unrecognized selector sent to instance 0xa9bc3a0'
*** First throw call stack:
(
0 CoreFoundation 0x020c75e4 __exceptionPreprocess + 180
1 libobjc.A.dylib 0x01e4a8b6 objc_exception_throw + 44
2 CoreFoundation 0x02164903 -[NSObject(NSObject) doesNotRecognizeSelector:] + 275
3 CoreFoundation 0x020b790b ___forwarding___ + 1019
4 CoreFoundation 0x020b74ee _CF_forwarding_prep_0 + 14
5 Foundation 0x006e18ed -[NSConcreteMutableAttributedString replaceCharactersInRange:withString:] + 39
6 Foundation 0x006e255a -[NSConcreteMutableAttributedString initWithString:attributes:] + 293
7 UIKit 0x01172bc6 -[UILabel _setText:] + 97
8 UIKit 0x01172d84 -[UILabel setText:] + 40
9 App 0x00047ebd -[PiccImageCategoriesViewController tableView:cellForRowAtIndexPath:] + 1533
10 UIKit 0x010b461f -[UITableView _createPreparedCellForGlobalRow:withIndexPath:] + 412
11 UIKit 0x010b46f3 -[UITableView _createPreparedCellForGlobalRow:] + 69
12 UIKit 0x01098774 -[UITableView _updateVisibleCellsNow:] + 2378
13 UIKit 0x010abe95 -[UITableView layoutSubviews] + 213
14 UIKit 0x01030267 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 355
15 libobjc.A.dylib 0x01e5c81f -[NSObject performSelector:withObject:] + 70
16 QuartzCore 0x00c8e2ea -[CALayer layoutSublayers] + 148
17 QuartzCore 0x00c820d4 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 380
18 QuartzCore 0x00c81f40 _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 26
19 QuartzCore 0x00be9ae6 _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 294
20 QuartzCore 0x00beae71 _ZN2CA11Transaction6commitEv + 393
21 QuartzCore 0x00beb544 _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 92
22 CoreFoundation 0x0208f4ce __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 30
23 CoreFoundation 0x0208f41f __CFRunLoopDoObservers + 399
24 CoreFoundation 0x0206d344 __CFRunLoopRun + 1076
25 CoreFoundation 0x0206cac3 CFRunLoopRunSpecific + 467
26 CoreFoundation 0x0206c8db CFRunLoopRunInMode + 123
27 GraphicsServices 0x027779e2 GSEventRunModal + 192
28 GraphicsServices 0x02777809 GSEventRun + 104
29 UIKit 0x00fc5d3b UIApplicationMain + 1225
30 App 0x0001406d main + 141
31 libdyld.dylib 0x02f4d70d start + 1
32 ??? 0x00000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
Thanks
The return of [[self.categoryArr objectAtIndex:indexPath.row] objectForKey:#"title"]; is a array of NSString, categoryLabel.text = [NSString stringWithFormat:#"%#", /*the return array*/]; this is the problem.
Maybe what you want is:
NSArray *categoryDetailArr = [[self.categoryArr objectAtIndex:indexPath.section] objectForKey:#"title"];
categoryLabel.text = [[categoryDetailArr objectAtIndex:indexPath.row];
Write this code
categoryLabel.text = [[[self.categoryArr objectAtIndex:0] objectForKey:#"title"]objectAtIndex:indexPath.row];
instead OF
categoryLabel.text = [NSString stringWithFormat:#"%#",[[self.categoryArr objectAtIndex:indexPath.row] objectForKey:#"title"];
And plz check that in UITableView dataSource methods i.e
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [categoryLabel objectAtIndex:0]valueForKey:#"selected"].count;
}
OR
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [categoryLabel objectAtIndex:0]valueForKey:#"title"].count;
}
I have an iPhone app which fetches user information (first name, last name, city) in JSON format from different social networks.
This works mostly well, but one of the social networks returns the city as a number instead of a string (actually I should made one more REST call to map this number to a city name... but for now I just want to display the number).
And when I try to display that number in a UILabel I get the exception (here fullscreen):
2014-02-15 11:24:16.194 MyAuth[8872:a0b] -[__NSCFNumber length]: unrecognized selector sent to instance 0xb074f90
2014-02-15 11:24:16.203 MyAuth[8872:a0b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber length]: unrecognized selector sent to instance 0xb074f90'
*** First throw call stack:
(
0 CoreFoundation 0x01bb15e4 __exceptionPreprocess + 180
1 libobjc.A.dylib 0x019348b6 objc_exception_throw + 44
2 CoreFoundation 0x01c4e903 -[NSObject(NSObject) doesNotRecognizeSelector:] + 275
3 CoreFoundation 0x01ba190b ___forwarding___ + 1019
4 CoreFoundation 0x01ba14ee _CF_forwarding_prep_0 + 14
5 Foundation 0x015798ed -[NSConcreteMutableAttributedString replaceCharactersInRange:withString:] + 39
6 Foundation 0x0157a55a -[NSConcreteMutableAttributedString initWithString:attributes:] + 293
7 UIKit 0x0084fbc6 -[UILabel _setText:] + 97
8 UIKit 0x0084fd84 -[UILabel setText:] + 40
9 MyAuth 0x0000a296 -[UserViewController viewDidLoad] + 678
10 UIKit 0x007b6318 -[UIViewController loadViewIfRequired] + 696
11 UIKit 0x007b65b4 -[UIViewController view] + 35
12 UIKit 0x007d03e2 -[UINavigationController _startCustomTransition:] + 778
13 UIKit 0x007dd0c7 -[UINavigationController _startDeferredTransitionIfNeeded:] + 688
14 UIKit 0x007ddcb9 -[UINavigationController __viewWillLayoutSubviews] + 57
15 UIKit 0x00917181 -[UILayoutContainerView layoutSubviews] + 213
16 UIKit 0x0070d267 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 355
17 libobjc.A.dylib 0x0194681f -[NSObject performSelector:withObject:] + 70
18 QuartzCore 0x054e12ea -[CALayer layoutSublayers] + 148
19 QuartzCore 0x054d50d4 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 380
20 QuartzCore 0x054d4f40 _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 26
21 QuartzCore 0x0543cae6 _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 294
22 QuartzCore 0x0543de71 _ZN2CA11Transaction6commitEv + 393
23 QuartzCore 0x0543e544 _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 92
24 CoreFoundation 0x01b794ce __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 30
25 CoreFoundation 0x01b7941f __CFRunLoopDoObservers + 399
26 CoreFoundation 0x01b57344 __CFRunLoopRun + 1076
27 CoreFoundation 0x01b56ac3 CFRunLoopRunSpecific + 467
28 CoreFoundation 0x01b568db CFRunLoopRunInMode + 123
29 GraphicsServices 0x031a09e2 GSEventRunModal + 192
30 GraphicsServices 0x031a0809 GSEventRun + 104
31 UIKit 0x006a2d3b UIApplicationMain + 1225
32 MyAuth 0x0000ab7d main + 141
33 libdyld.dylib 0x02518725 start + 0
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
So I go to my JSON parsing code:
- (User*)createUserFromJson:(id)json
{
if (![json isKindOfClass:[NSDictionary class]]) {
NSLog(#"Parsing response failed");
return nil;
}
NSDictionary *dict = json[#"response"][0];
User *user = [[User alloc] init];
user.key = kVK;
user.userId = dict[#"uid"];
user.firstName = dict[#"first_name"];
user.lastName = dict[#"last_name"];
user.city = dict[#"city"]; // THE PROBLEMATIC LINE
user.avatar = dict[#"photo_big"];
user.female = (2 == [dict[#"female"] intValue]);
return user;
}
and try to change it to:
user.city = [NSString stringWithFormat:#"%d", dict[#"city"]];
but then I get the compile-time warning (here fullscreen):
Format specifies type 'int' but the argument has type 'id'
So my question is how to solve this issue cleanly (w/o Xcode warnings) and robust (when fetched JSON data happens to be a string)?
The fastest solution is:
[NSString stringWithFormat:#"%#", dict[#"city"]];
which will take the description of the string or the number and convert that into a string.
In the future you may want to use:
if ([1dict[#"city"] isKindOfClass:[NSNumber class]]) { ...
to check what you have received and work with it specifically. i.e. to do your lookup and to not use stringWithFormat: when you actually already have a string (because it's inefficient).