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;
}
Related
I have a custom class oject that I want to save using NSUserDefaults, this is how I saving it:
Shift.m
-(void)encodeWithCoder:(NSCoder*)encoder
{
[encoder encodeObject:self.date forKey:#"date"];
[encoder encodeObject:self.startTime forKey:#"startTime"];
[encoder encodeObject:self.endTime forKey:#"endTime"];
}
- (id)initWithCoder:(NSCoder *)decoder {
if(self = [super init]) {
self.date = [decoder decodeObjectForKey:#"date"];
self.startTime = [decoder decodeObjectForKey:#"startTime"];
self.endTime = [decoder decodeObjectForKey:#"endTime"];
}
return self;
}
MyTableViewController.m:
-(void)saveCustomObject:(id)object forKey:(NSString*)key
{
NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject:object];
[[NSUserDefaults standardUserDefaults] setObject:encodedObject forKey:key];
}
-(NSArray*)getCustomObjectForKey:(NSString*)key
{
NSData *encodedObject = [[NSUserDefaults standardUserDefaults] objectForKey:key];
NSArray *shifts=[NSArray arrayWithObjects:[NSKeyedUnarchiver unarchiveObjectWithData:encodedObject], nil];
return shifts;
}
It seems it works fine when debugging, but when I try to access one of the object properties, for example on tableView: cellForRowAtIndexPath: like that:
Shift *currentShift=[self.shifts objectForIndex:indexPath.row];
NSLog(#"%#",currentShift.startTime.description);
It crashes with that crash message:
2016-03-19 09:04:05.913 MyApp[9654:4249448] -[__NSArrayM startTime]: unrecognized selector sent to instance 0x7ff81b449c10
2016-03-19 09:04:05.924 MyApp[9654:4249448] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayM startTime]: unrecognized selector sent to instance 0x7ff81b449c10'
*** First throw call stack:
(
0 CoreFoundation 0x000000010e3e9e65 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x000000010de62deb objc_exception_throw + 48
2 CoreFoundation 0x000000010e3f248d -[NSObject(NSObject) doesNotRecognizeSelector:] + 205
3 CoreFoundation 0x000000010e33f90a ___forwarding___ + 970
4 CoreFoundation 0x000000010e33f4b8 _CF_forwarding_prep_0 + 120
5 Mehuyavut count 0x000000010d95a8e8 -[shiftsTableViewViewController tableView:cellForRowAtIndexPath:] + 600
6 UIKit 0x000000010e8efe43 -[UITableView _createPreparedCellForGlobalRow:withIndexPath:willDisplay:] + 766
7 UIKit 0x000000010e8eff7b -[UITableView _createPreparedCellForGlobalRow:willDisplay:] + 74
8 UIKit 0x000000010e8c4a39 -[UITableView _updateVisibleCellsNow:isRecursive:] + 2996
9 UIKit 0x000000010e8f901c -[UITableView _performWithCachedTraitCollection:] + 92
10 UIKit 0x000000010e8dfedc -[UITableView layoutSubviews] + 224
11 UIKit 0x000000010e84d4a3 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 703
12 QuartzCore 0x000000011231959a -[CALayer layoutSublayers] + 146
13 QuartzCore 0x000000011230de70 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 366
14 QuartzCore 0x000000011230dcee _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24
15 QuartzCore 0x0000000112302475 _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 277
16 QuartzCore 0x000000011232fc0a _ZN2CA11Transaction6commitEv + 486
17 QuartzCore 0x000000011233037c _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 92
18 CoreFoundation 0x000000010e315367 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 23
19 CoreFoundation 0x000000010e3152d7 __CFRunLoopDoObservers + 391
20 CoreFoundation 0x000000010e30af2b __CFRunLoopRun + 1147
21 CoreFoundation 0x000000010e30a828 CFRunLoopRunSpecific + 488
22 GraphicsServices 0x0000000111ba6ad2 GSEventRunModal + 161
23 UIKit 0x000000010e796610 UIApplicationMain + 171
24 Mehuyavut count 0x000000010d95b5af main + 111
25 libdyld.dylib 0x0000000110b2592d start + 1
26 ??? 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
Any one knows why?
Thank you!
It seems like you want Shift *currentShift=[self.shifts objectForIndex:indexPath.row] to give you 1 Shift object, but what it really does is returning a NSArray. You basically call a startTime method in NSArray, and since it doesn't exist, your program fails.
It seems like NSLog(#"%#",currentShift.startTime.description) is the line doing that. Confirm by commenting out the NSLog. It shouldn't give you a crash.
If this hypothesis is fine, check if [currentShift isKindOfClass:[NSArray class]] is true.
If it is, a bug you have in this line:
NSArray *shifts=[NSArray arrayWithObjects:[NSKeyedUnarchiver unarchiveObjectWithData:encodedObject], nil];
You also don't really show how your - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section looks like. You must return proper number of entries there.
You're making self.shifts be an NSArray, but you use objectForKey, which is available for dictionaries. It's not available for arrays. I think you wanted objectAtIndex instead.
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);
}
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"]]).
I've been trying to solve this problem for the past two days but I just can't find why it occurs, so I took it here to ask if you guys have any idea about it.
So I have a UITableView which I display some items in. I also have a UITableViewCell which I use as the cells.
I register the nib with my table view in the viewDidLoad:
[self.QuickPickDetailsTV registerNib:[UINib nibWithNibName:#"QuickPickItemCell"
bundle:[NSBundle mainBundle]]
forCellReuseIdentifier:#"QuickPickItemCellReuseID"];
Then in the tableView:cellForRowAtIndexPath:, I reuse, populate, and return the cell as below:
static NSString *CellIdentifier = #"QuickPickItemCellReuseID";
QuickPickItemCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[QuickPickItemCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
NSDictionary *quickPickItem = [self.myQuickPickItems objectAtIndex:indexPath.row];
NSString *theQuickPickItemName = [quickPickItem valueForKey:#"name"];
[cell.mName setFont:[UIFont fontWithName:#"OpenSans" size:16]];
[cell.mName setText:NSLocalizedString(theQuickPickItemName, nil)];
return cell;
The method above gets called for the number of items it should display (as expected), and crashes with an strange error after the last cell is returned:
2014-08-02 13:03:38.008 TestApp[49701:607] -[__NSArrayI length]: unrecognized selector sent to instance 0x2e92fde0
2014-08-02 13:03:38.010 TestApp[49701:607] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayI length]: unrecognized selector sent to instance 0x2e92fde0'
*** First throw call stack:
(
0 CoreFoundation 0x044f21e4 __exceptionPreprocess + 180
1 libobjc.A.dylib 0x033888e5 objc_exception_throw + 44
2 CoreFoundation 0x0458f243 -[NSObject(NSObject) doesNotRecognizeSelector:] + 275
3 CoreFoundation 0x044e250b ___forwarding___ + 1019
4 CoreFoundation 0x044e20ee _CF_forwarding_prep_0 + 14
5 UIKit 0x01ff8463 -[UILabel _shadow] + 45
6 UIKit 0x01ff98c2 -[UILabel drawTextInRect:] + 70
7 UIKit 0x01ffbdfc -[UILabel drawRect:] + 98
8 UIKit 0x01eaa453 -[UIView(CALayerDelegate) drawLayer:inContext:] + 504
9 QuartzCore 0x00dbaf39 -[CALayer drawInContext:] + 123
10 QuartzCore 0x00dbae6a _ZL16backing_callbackP9CGContextPv + 96
11 QuartzCore 0x00ca94fc CABackingStoreUpdate_ + 2656
12 QuartzCore 0x00dbae02 ___ZN2CA5Layer8display_Ev_block_invoke + 93
13 QuartzCore 0x00def2d7 x_blame_allocations + 15
14 QuartzCore 0x00dbac6d _ZN2CA5Layer8display_Ev + 1519
15 QuartzCore 0x00dbaeb9 -[CALayer _display] + 33
16 QuartzCore 0x00dba676 _ZN2CA5Layer7displayEv + 144
17 QuartzCore 0x00dbae93 -[CALayer display] + 33
18 QuartzCore 0x00daf043 _ZN2CA5Layer17display_if_neededEPNS_11TransactionE + 323
19 QuartzCore 0x00daf0bc _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 38
20 QuartzCore 0x00d157fa _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 294
21 QuartzCore 0x00d16b85 _ZN2CA11Transaction6commitEv + 393
22 QuartzCore 0x00d17258 _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 92
23 CoreFoundation 0x044ba36e __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 30
24 CoreFoundation 0x044ba2bf __CFRunLoopDoObservers + 399
25 CoreFoundation 0x04498254 __CFRunLoopRun + 1076
26 CoreFoundation 0x044979d3 CFRunLoopRunSpecific + 467
27 CoreFoundation 0x044977eb CFRunLoopRunInMode + 123
28 GraphicsServices 0x047e95ee GSEventRunModal + 192
29 GraphicsServices 0x047e942b GSEventRun + 104
30 UIKit 0x01e3bf9b UIApplicationMain + 1225
31 TestApp 0x00002c92 main + 130
32 TestApp 0x00002c05 start + 53
33 ??? 0x00000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
I have searched all my code but I don't send length to any object in my code. I don't know where is the crash coming from since it is shown to be on my main.m.
I have tried turning on NSZombies as well, but I didn't get any warnings about released objects.
Any help will be appreciated!
Thanks
I am getting this crash showing up in BugSense:
-[NSConcreteData count]: unrecognized selector sent to instance 0x14e57f10 - NSInvalidArgumentException
in this code:
+ (NSMutableArray *)applyFilters:(NSMutableArray *)theItems fromFilter:(NSDictionary *)filters
{
NSMutableArray *items = [[NSMutableArray alloc] initWithArray:theItems];
if ([[filters allKeys] count] > 0)
{
NSMutableArray *tempFilteredItems = [[NSMutableArray alloc] init];
for (NSString *key in [filters allKeys])
{
NSMutableString *convertedKey = [NSMutableString stringWithString:key];
[convertedKey replaceOccurrencesOfString:#" "
withString:#"_"
options:NSCaseInsensitiveSearch
range:NSMakeRange(0, [convertedKey length])];
NSArray *tempFilterAttributes = [NSArray arrayWithArray:filters[key]];
for (NSDictionary *item in items)
{
if (![[item[convertedKey] componentsSeparatedByString:#"*"] firstObjectCommonWithArray:tempFilterAttributes])
{
if (![tempFilteredItems containsObject:item])
{
[tempFilteredItems addObject:item];
}
}
}
[items removeObjectsInArray:tempFilteredItems];
[tempFilteredItems removeAllObjects];
}
}
return items;
}
Why/how is this happening?
Stack trace is:
CoreFoundation <redacted> + 130
1 libobjc.A.dylib objc_exception_throw + 38
2 CoreFoundation <redacted> + 202
3 CoreFoundation <redacted> + 706
4 CoreFoundation _CF_forwarding_prep_0 + 24
5 CoreFoundation <redacted> + 28
6 Video Games +[Helper applyFilters:fromFilter:] (Helper.m:2862)
7 Video Games -[WishlistViewController loadUp] (WishlistViewController.m:409) + 29303
8 Video Games -[WishlistViewController viewWillAppear:] (WishlistViewController.m:363) + 27955
9 UIKit <redacted> + 374
10 UIKit <redacted> + 612
11 UIKit <redacted> + 572
12 UIKit <redacted> + 44
13 UIKit <redacted> + 184
14 UIKit <redacted> + 380
15 QuartzCore <redacted> + 142
16 QuartzCore <redacted> + 350
17 QuartzCore <redacted> + 16
18 QuartzCore <redacted> + 228
19 QuartzCore <redacted> + 314
20 UIKit <redacted> + 126
21 CoreFoundation <redacted> + 20
22 CoreFoundation <redacted> + 286
23 CoreFoundation <redacted> + 738
24 CoreFoundation CFRunLoopRunSpecific + 524
25 CoreFoundation CFRunLoopRunInMode + 106
26 GraphicsServices GSEventRunModal + 138
27 UIKit UIApplicationMain + 1136
28 Video Games main (main.m:16) + 888911
29 libdyld.dylib <redacted> + 2
The problem has nothing to do with the code that you provided. The error messages says that the message count was sent to the class NSConcreteData, which is essentially the same as NSData, and such a class method does not exist.
I suggest that you set an exception breakpoint (in Xcode select left the breakpoint navigator, click + left bottom, and select add exception breakpoint).
When you execute the app, it will stop at the faulty instruction.
EDIT (due to the stack trace you provided now):
The stack trace indeed says that your method applyFilters:fromFilter: is responsible for the crash. The only place where the message count is sent in this method, is the statement [[filters allKeys] count]. It looks then that count is sent to an NSConcreteData object, and not to an NSArray object as you might have expected. One reason could be that the argument filters, that should be a NSDictionary, is an object of a different type.
So when the app stops at the exception breakpoint, please check the class of the instance filters.