There are some similar questions that already exist on StackOverflow. I did check them out, and in most cases it returns nil because the NSMutableArray has not been initialised. But in my case I did initialise it.
Here's part of my code :
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
self.storedTimeZones = [[NSMutableArray alloc] init];
NSData *storedData = [[NSUserDefaults standardUserDefaults] dataForKey:#"timeZones"];
if (storedData != nil ) {
self.storedTimeZones = [NSKeyedUnarchiver unarchiveObjectWithData:storedData];
}
NSString *str = [self.smallRegionArray[indexPath.row] stringByReplacingOccurrencesOfString:#"_" withString:#" "];
[self.storedTimeZones addObject: str];
NSLog(str); //the string was printed successfully.
NSLog(#"%lu", (unsigned long)self.storedTimeZones.count); //'0' was printed
}
update
#Caleb was right, [NSKeyedUnarchiver unarchiveObjectWithData:storedData returned nil. I solved it by doing this:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
self.storedTimeZones = [[NSMutableArray alloc] init];
NSData *storedData = [[NSUserDefaults standardUserDefaults] dataForKey:#"timeZones"];
NSMutableArray *ary = [NSKeyedUnarchiver unarchiveObjectWithData:storedData];
if (ary != nil ) {
self.storedTimeZones = ary;
}
NSString *str = [self.smallRegionArray[indexPath.row] stringByReplacingOccurrencesOfString:#"_" withString:#" "];
[self.storedTimeZones addObject: str];
NSLog(str);
NSLog(#"%lu", (unsigned long)self.storedTimeZones.count); //Now it prints `1`
}
But in my case I did initialise it.
You did, but then you replaced it. Here's the initializing line:
self.storedTimeZones = [[NSMutableArray alloc] init];
but then you assign a different value:
self.storedTimeZones = [NSKeyedUnarchiver unarchiveObjectWithData:storedData];
and at this point, self.storedTimeZones may be either a non-mutable instance of NSArray, or some entirely different object, or nil. I'd guess it's the latter since no exception is thrown when you call -addObject:. That the count is 0 also makes sense if self.storedTimeZones is nil, since the result of messaging nil is nil or 0 or NO, depending on what type you expect.
All you really need to do to properly diagnose the problem is to examine self.storedTimeZones near your last NSLog statement. Set a breakpoint and look at the contents of that property. Useful commands will be:
po self.storedTimeZones
po [self.storedTimeZones class]
You're trying to assign the object to the entire mutable array, you're not adding a object to it.
That's not the way it works.
Try this:
[self.storedTimeZones addObject:
[NSKeyedUnarchiver unarchiveObjectWithData:storedData]];
Or this
[self.storedTimeZones addObjectsFromArray:[NSKeyedUnarchiver unarchiveObjectWithData:storedData]];
Or this
self.storedTimeZones = [NSArray alloc]; // Note: not a mutable array
[self.storedTimeZones initWithArray:[NSKeyedUnarchiver unarchiveObjectWithData:storedData]];
You've never told us if the contents of the keyedUnarchiver is an array, but we expect it is.
In either case, if this is the only time you add info to the array, you don't need to make it mutable.
Good luck.
Related
I have a NSMutabelArray and I want to do some additions inside of it. I do this by calling a functions with then create a subarray with the items where the calculations have to be done on.
- (NSDecimalNumber *)calculate:(NSMutableArray *)arrayToCalculate {
while ([arrayToCalculate containsObject:(#"+")]) {
NSUInteger signeLocation = [arrayToCalculate indexOfObject:(#"+")];
[arrayToCalculate replaceObjectAtIndex:(signeLocation-1)
withObject:([[arrayToCalculate objectAtIndex:(signeLocation-1)]
decimalNumberByAdding:[arrayToCalculate objectAtIndex:(signeLocation+1)]])];
[arrayToCalculate removeObjectsAtIndexes:
[NSIndexSet indexSetWithIndexesInRange:NSMakeRange((signeLocation), 2)]];
}
return [arrayToCalculate lastObject];
}
I initialised the arrayToCalculate by:
NSMutableArray *subArray =
[inputArray subarrayWithRange:(rangeOfCalculationItems)];
Every time I run this code it crashes. I am pretty sure it is bc I used subarray on an NSMutableArray and initialised it as NSMutableArray even when the message gives me back a NSArray, but I don't know how I could fix it or it is even the problem.
I copied your method and tested it like this:
NSArray *items = #[
[[NSDecimalNumber alloc] initWithString:#"1"],
#"+",
[[NSDecimalNumber alloc] initWithString:#"2"]
];
NSLog(#"%g", [self calculate: [items mutableCopy]].floatValue);
The code works and the printed result was 3. Your issue must be somewhere else. Are you sure your array is in fact mutable? Note [items mutableCopy].
I have the following situation where
I have an NSMutableArray filled with an xml file which I want to search.
When I enter something in the search field I get this Error:
-[NSCFString countByEnumeratingWithState:objects:count:]: unrecognized selector sent to instance 0x5b388b0
What does it means and how can I fix it??
I suppose the error is somewhere around here.
- (void)searchTableView{
searchedList = [[NSMutableArray alloc] init];
NSLog(#"new list %#", searchedList);
NSString *searchText = searchBar.text;
NSMutableArray *searchArray = [[NSMutableArray alloc] init];
for (NSDictionary *dictionary in list) {
NSArray *array = [dictionary objectForKey:#"TITLE"];
[searchArray addObjectsFromArray:array];
}
for (NSString *TempArray in searchArray) {
NSRange titleResults = [TempArray rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (titleResults.length > 0)
[searchedList addObject:TempArray];
}
[searchArray release];
searchArray = nil;
}
it means you are calling a method designed for an NSArray (countByEnumeratingWithState:objects:count on a NSString.
I don't know ifthis code is copy/paste from yours, but if so, at the end where you use [searchList addObject:TempArray] you don't have an object named searchList.
Also, work on your naming conventions. big time.
I know the instructions are all over of how to read a .csv file in objective c then pass it to an NSMuatbleArray, but I'm getting problems when I assign it to a mutableArray. I've spent hours of checking online and trying to fix it, but nothing helped.
Here is my objective c code:
NSError *err;
NSString *filePath = [NSString stringWithContentsOfFile:#"/users/Mike/Desktop/Book1.csv" encoding:NSUTF8StringEncoding error:&err];
NSString *replace = [filePath stringByReplacingOccurrencesOfString:#"\"" withString:#""];
NSString *something = [replace stringByReplacingOccurrencesOfString:#"," withString:#"\n"];
NSMutableArray *columns = [[NSMutableArray alloc] initWithObjects:[something componentsSeparatedByString:#"\n"], nil];
NSLog(#"%#", filePath);
NSLog(#"%#", something);
NSLog(#"%#", columns);
Here is the output:
My App[1854:54976] Kitchen,Bathroom,Dinning Room,Living Room
My App[1854:54976] Kitchen
Bathroom
Dinning Room
Living Room
My App[1854:54976] (
(
Kitchen,
Bathroom,
"Dinning Room",
"Living Room"
)
)
The problem is that the output of the array comes with commas and quotations which I eliminated.
What I need is for the array "columns" to come out like the string "something".
Update
I took away the two strings of "replace" and "something" and switched the array to:
collumns = [[NSMutableArray alloc] initWithObjects:[filePath componentsSeparatedByString:#","], nil];
Now I'm having trouble loading it to a table view. Here's my code for that.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"firstCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
cell.textLabel.text = [columns objectAtIndex:indexPath.row];
return cell;
}
The app just crashes with an unexplaned reason, but when I make another array manually, it works.
This one works:
NSMutableArrayrow = [[NSMutableArray alloc] initWithObjects:#"First", #"Second", nil];
Your code is a bit muddled, and contains one error that is the cause of your unexplained parenthesis.
Why replace quotes with nothing when there are no quotes in the
source data?
Why replace commas with line breaks, and then split the string into
an array of strings on the line breaks (which gets rid of the line
breaks entirely)? Why not just split the string into an array using
commas and skip the intermediate step?
Finally, and most seriously, the method initWithObjects wants a
comma-delimited set of objects, then a nil. You are passing it an
array, and nil. So what you are getting as a result is a mutable
array that contains a single object, an immutable array. This is
almost certainly not what you want.
This line:
NSMutableArray *columns =
[[NSMutableArray alloc] initWithObjects:
[something componentsSeparatedByString:#"\n"], nil];
...is wrong.
You would use initWithObjects like this:
NSMutableArray *columns =
[[NSMutableArray alloc] initWithObjects: #"one", #"two", #"three", nil];
Note how I'm passing in a comma-separated list of objects, and then a nil. Your use of initWithObjects is passing in a single object, an array, and then a nil. You won't get a mutable array that contains the objects from the source array - you'll get a mutable array that contains your starting immutable array.
It should be written like this instead:
NSMutableArray *columns = [[something componentsSeparatedByString:#"\n"]
mutableCopy];
Or better yet, do it in 2 steps so it's clear whats going on:
NSArray *tempArray = [something componentsSeparatedByString:#"\n"];
NSMutableArray *columns = [tempArray mutableCopy];
I am in my IOS application in which i am getting ID from server which i am saving in string and then add strings in NSMutableArray.I am not getting perfect method by which i can add the strings in array and use the array outside the scope.
Here is my code Please help me out::
- (void)flickrAPIRequest:(OFFlickrAPIRequest *)inRequest didCompleteWithResponse:(NSDictionary *)inResponseDictionary
{
NSMutableArray *array=[[NSMutableArray alloc]init];
i=0;
NSLog(#"%s %# %#", __PRETTY_FUNCTION__, inRequest.sessionInfo, inResponseDictionary);
if (inRequest.sessionInfo == kUploadImageStep)
{
snapPictureDescriptionLabel.text = #"Setting properties...";
NSLog(#"%#", inResponseDictionary);
NSString* photoID =[[inResponseDictionary valueForKeyPath:#"photoid"] textContent];
flickrRequest.sessionInfo = kSetImagePropertiesStep;
// for uploading pics on flickr we call this method
[flickrRequest callAPIMethodWithPOST:#"flickr.photos.setMeta" arguments:[NSDictionary dictionaryWithObjectsAndKeys:photoID, #"photo_id", #"PicBackMan", #"title", #"Uploaded from my iPhone/iPod Touch", #"description", nil]];
[self.array addObject:photoID];
arr=array[0];
counterflicker++;
NSLog(#" Count : %lu", (unsigned long)[array count]);
}
How can i add the photoID(Strings) in the array?
Please help me out..
for adding NSString in NSMutableArray is like this
NSString *str = #"object";
NSMutableArray *loArr = [[NSMutableArray alloc] init];
[loArr addObject:str];
In your code Why are you using self.array ? just write like this. [array addObject:photoID];
self keyword is used for global variables but here in your code
"array" is a local variable .So need of self.array
[array addObject:photoID];
Before adding check that photoID is nil or not
if (photoID.length > 0) {
[array addObject:photoID];
}
I observe that in your code. you declare mutable array in local scope.
So just use
[array addObject:photoID];
Instead of
[self.array addObject:photoID];
May be you are create property for this array with same name, then you need to alloc it.
If you create a property for this then remove local declaration and alloc array like this.
self.array=[[NSMutableArray alloc]init];
and then use
[self.array addObject:photoID];
getting a "Thread 1: EXC_BAD_ACCES(code=2, adress=0xbf7fffffc)" error at
NSArray *tempArray ] [lijstString componentsSeperatedByString:#","];
What can i do about this?
This is the whole codepart:
-(NSMutableArray *)lijstArray{
NSString *lijstString = self.details[#"lijst"];
NSArray *tempArray = [lijstString componentsSeparatedByString:#", "];
self.lijstArray = [NSMutableArray array];
for (NSString *lijstValue in tempArray) {
[self.lijstArray addObject:[lijstValue stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
}
return self.lijstArray;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 2;
}
Your lijstArray getter function is infinitely recursive. Assuming lijstArray is an #property, every time you use self.lijstArray you are calling the instance method lijstArray if used as a getter or setLijstArray if used as a setter.
You are using self.lijstArray three times. The first use on the left part of the assignment operator is only calling [self setLijstArray: ... ] so while that will trample the _lijstArray iVar, it will not cause recursion.
You cause recursion in two places, though once is enough. First is with [self.lijstArray addObject: ... ] which is the same as [[self lijstArray] addObject: ... ]. This causes infinite recursion.
And then with return self.lijstArray which is the same as return [self lijstArray] -- again the lijstArray instance method is calling itself. This also causes infinite recursion.
Incidentally the stack trace would be informative-- you'd have a very deep stack.
try this:
-(NSMutableArray *)lijstArray{
if(!_lijstArray){ //If you need get new lijstArray always, comment this line, and below "}"
NSString *lijstString = self.details[#"lijst"];
NSArray *tempArray = [lijstString componentsSeparatedByString:#", "];
_lijstArray = [NSMutableArray array];
for (NSString *lijstValue in tempArray) {
[_lijstArray addObject:[lijstValue stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
}
}
return _lijstArray;
}
Check to make sure the line:
self.details[#"list"];
Is not null. Also check to make sure tempArray and lijstString are being allocated and initialized.