how to convert the value of nsarray to integer value - iphone

I working on grouped table view based work in that in that i want to convert the value of NSarray into integer for specifing to section value of numberOfRowsInSection but it throws expection on putting following code.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
int sec;
if (section == 0){ sec=6; }
else if(section == 1){ sec=6; }
else if(section == 2){
sec=[[rsvn_detail objectAtIndex:0] objectForKey:#"totalrecord"];
}
return sec;
}
Anybody help to recify it advance thanks for your suggestion
Regards,
sathish

NSArray and NSDictionary can only hold Objective-C objects. An int is not an object. It is likely the number is wrapped as an NSNumber. To convert an NSNumber back to an int, call -intValue:
sec = [[[rsvn_detail objectAtIndex:0] objectForKey:#"totalrecord"] intValue];
// ^^^^^^^^
Of course, make sure rsvn_detail is really an NSArray of NSDictionary. Without -intValue won't cause exceptions, only compiler warning/error will be raised.

What is the exception? Seems that [[rsvn_detail objectAtIndex:0] objectForKey:#"totalrecord"]; is causing the problem.

Related

How to allow a user to delete a comment only if they are the user that posted it with canEditRowAtIndexPath:

I want to allow a user to delete a comment only if they are the user that posted it.
I'm using the canEditRowAtIndexPath: method and am trying the following. The delete is no longer showing after I include this conditional.
if (userIdNumber == aNum) {
return YES;
}
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return YES if you want the specified item to be editable.
NSString *savedValue = [[NSUserDefaults standardUserDefaults]
stringForKey:#"userId"];
NSNumber *userIdNumber = [userId objectAtIndex:indexPath.row];
NSNumber *aNum = [NSNumber numberWithInteger: [savedValue integerValue]];
NSLog(#"savedValue is %#",savedValue);
NSLog(#"aNum is %#",aNum);
NSLog(#"userIdNumber is %#",userIdNumber);
if (userIdNumber == aNum) {
return YES;
}
else {
return NO;
}
}
I think you are using == operator to compare two NSNumbers. Once compare two numbers by using isEqualToNumber: method like below.
if([userIdNumber isEqualToNumber:aNum]){ return YES;}else{ return NO;}
As hinted by #Hot Licks, performing comparison of Objective-C objects requires more than just comparing their pointer values; you need to use the isEqual: method:
return [userIdNumber isEqual:aNum];
(further more if the objects were NSString then you need to use [NSString isEqualToString:]).

Condition always fails though the comparative values seems correct in iOS

When I check the value of number in nslog it shows '0'
NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile: path];
NSNumber *number=[data objectForKey:#"serial"];
NSLog(#"%#",number);
if(number ==0 )
{
imgButton.hidden=YES;
}
But the condition always fails , I also changed the code like this
NSString *number=[data objectForKey:#"serial"]
NSLog(#"%#",number);
if(number == #"0" )
{
imgButton.hidden=YES;
}
But here too the condition fail ,What is the issue with this?
In the first code you are checking a NSNumber, object, against an int.
The correct check is:
if([number intValue] == 0) {
imgButton.hidden = YES;
}
In the second code you are checking two NSString, but you have to use the "isEqualToString" method and not "==". The correct code is:
if([number isEqualToString:#"0"]) {
imgButton.hidden = YES;
}
NSNumber is an object, 0 is an integer (a primitive type). They will never be equal. But you can change the comparison like this [number intValue] == 0 and this will work when the value of your NSNumber is 0.
On the string comparison, you should use the method
isEqualToString:NSString *)string
for the comparison.
For NSNumbers its
isEqualToNumber:(NSNumber *)number
Because otherwise you arent comparing if they have the same value, but if they are stored in identical memory space.

Why is NSArray objectAtIndex:section for tableView titleForHeaderInSection error: index 0 beyond bounds for empty array

It's so wierd:
_tableDataSectionTitles is a property of this UITableViewController subclass & an NSArray.
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
NSLog(#"%#", _tableDataSectionTitles); // returns: ( "string" )
NSLog(#"%#", [_tableDataSectionTitles objectAtIndex:0]); // returns: "string"
NSLog(#"%i", section); // returns 0
NSLog(#"%#", [_tableDataSectionTitles objectAtIndex:section]; // returns "string"
return [_tableDataSectionTitles objectAtIndex:section]; // returns: *** -[__NSArrayI objectAtIndex:]: index 0 beyond bounds for empty array
what's with that!? (everything else is working properly. I checked. Thrice.) (seriously though, this is like the first thing that it runs through, so nothing should be wrong here)
I've also tried it with out even using the array:
NSString *rep = [[NSString alloc] init];
if (section == 0) {
rep = #"Stuff";
} else { // doesn't even need it - it won't run through it anyway
//rep = [_tableDataSectionTitles objectAtIndex:section]; // commented out just to not have any doubts
}
return rep;
but still the same error. help!
The below code will help you to detect the wrong part of your code easly
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
NSString *title = #"Empty";
NSLog(#"count: %d", [_tableDataSectionTitles count]);
NSLog(#"section: %d", section);
if([_tableDataSectionTitles count] > section)
title = [_tableDataSectionTitles objectAtIndex:section]
return title;
}
Obviously, the error says [__NSArrayI objectAtIndex:]: index 0 beyond bounds for empty array
meaning, the array IS empty even though it shouldn't be. So am not sure what exactly the problem is but you can follow the following steps to debug the problem,
Check if it happening only for section 0. Instead of passing section to objectAtIndex, pass 0 and try.
Return the title only if the array is not empty,
if([_tableDataSectionTitles count] > 0)
{
return [_tableDataSectionTitles objectAtIndex:section];
}
else
{
return #"Default Title";
}
Have alloc init the array somewhere in your code..? may e in ViewDidLoad or the init method.? If not do that and try.
If you encounter again anything weird, let us know. Hope it helps..:)
Well, I've got it.
So, turns out that my _tableDataSectionContents array was empty while the _tableDataSectionTitles had one in it. so, I still don't understand why exactly it raised the error for a completely separate array, but it works now! thanks for all your help.

Objective-C: using if/else statement with Plist values

I'm sure this is really basic but I can't see what I'm doing wrong. Can someone help me understand where I'm going wrong please? I'm working in xcode. I'm trying to make different parts of my view appear depending on values saved in a property list. If the value assigned to a particular UITextField is equal to zero then I want to hide that UITextField. I'm trying to do this like this. gross is the name of a UITextField:
NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];
gross.text = [array objectAtIndex:7];
if ([array objectAtIndex:7 == 0]) {
gross.hidden = YES;
}
else {
gross.hidden = NO;
}
[array release];
I think the problem is something to do with how I've wrote the if/else statement. I know this is really basic but I don't quite understand where I'm going wrong. So Your help is much appreciated.
Code should read:
NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];
gross.text = [array objectAtIndex:7];
if ([[array objectAtIndex:7] isEqualToString:#"0"]) {
gross.hidden = YES;
} else {
gross.hidden = NO;
}
[array release];
This assumes that the object at index 7 of your array exists and is a string. If it's actually an NSNumber, then you should instead use the conditional
if ([[array objectAtIndex:7] intValue] == 0) {
Note the above line works for a string where the text contains an int, such as #"0" or #"7".
if ([[array objectAtIndex:7] intValue] == 0)
First mistake is position of closing ]. And second one is you probably have NSString in array, as you have assigned that in text property. So you need to convert it to int by using intValue.
If your array contains nsstring then your condition should look like:
if ([[array objectAtIndex:7] intValue] == 0) {
...
or
if ([[array objectAtIndex:7] isEqualToString:#"0"]) {
1st condition will work also if your array contains NSNumbers (not likely in your case as you assign array elements to text property), but will fail if string is not a valid number - in that case intValue will return 0 as well.
2nd condition will work fine if you're sure that your elements are strings and you want to compare exactly with #"0".
Your condition is equivalent to
if ([array objectAtIndex:0])
because == operator has greater priority and evaluates to 0. Comparing array's element to 0 directly also does not make sense as NSArray cannot contain nil objects anyway
It might be easier to get the length of the array first and make sure that it has enough elements and then start accessing the elements themselves.

Testing for contents of an NSArray without risking range error

I'm foolishly saying:
if ([imageCache objectAtIndex:index]) {
Problem is, on my first time through this, I haven't put ANYTHING in my NSMutableArray *imageCache, and this croaks with a range error.
How can I ask an NSMutableArray whether it has anything for a particular index?
The NSArray cluster class cannot store nil. So I think it is sufficient to simply check the bounds:
NSUInteger index = xyz;
if (index < [imageCache count]) {
id myObject = [imageCache objectAtIndex:index];
}
What I find really useful is having a safeObjectAtIndex: method. This will do the check for you and will return nil if the index is out of range.
Just create a new category on NSArray and include the following methods:
- (id)safeObjectAtIndex:(NSUInteger)index;
{
return ([self arrayContainsIndex:index] ? [self objectAtIndex:index] : nil);
}
- (BOOL)arrayContainsIndex:(NSUInteger)index;
{
return NSLocationInRange(index, NSMakeRange(0, [self count]));
}
if (index < [imageCache count])
...
This code answers your question. Unlike the accepted answer, this code handles passing in a negative index value.
if (!NSLocationInRange(index, NSMakeRange(0, [imageCache count]))) {
// Index does not exist
} else {
// Index exists
}
[imageCache count] will return the number of items in your array. Take it from there :-)
Check the number of items in the array first with [imageCache count]. Don't try to ask for anything with an index greater than that result.