I'm learning iOS but have an issue extracting data from a multidimensional NSMutableArray, I've looked at various solutions but have not yet found one..
I have an NSMutableArray like
{
"service_0" = {
"name" = "name1";
"description" = "description1";
};
"service_2" = {
"name" = "name2";
"description" = "description2";
};
Etc...
}
I wish to extract data into a new NSMutableArray (or NSArray) to get the following output for use in text labels such as = [myArray objectAtIndex:indexPath.row]
(
name1,
name2,
Etc...
)
What would be the best solution? Thanks
Assuming that is an array of dictionaries, unlike in the question...
NSArray *newArray = [oldArray valueForKeypath:#"name"];
You can make it mutable using mutableCopy, if you wish.
Related
I am new to Objective-C and I was looking for some help with my code. I want to search a word in a array.
#[#{
"name":"nick",
"Id":"2"
},
#{
"name":"Anna",
"Id":"4"
}]
I want to search name "nick" in array and fetch that complete object and create new array. I don't know how to do this in Objective-C.
NSArray * names = #[#{"name":"nick","Id":"2"},#{"name":"Anna","Id":"4"}];
NSMutableArray * results = [NSMutableArray arrayWithCapacity:1];
for ( NSDictionary * name in names )
{
if ( [name[#"name"] isEqualToString:#"nick"] )
{
[results addObject:name];
}
}
Something like that. Written from memory and not tested.
I'm trying to make an array of array of strings so that I can eventually pull out something like ArrayOfArrays[0][1] = "hi".
NSString *ArrayOne[] = {#"hello", #"hi"};
NSString *ArrayTwo[] = {#"goodbye", #"bye"};
NSArray *ArrayOfArrays[] = {#[*ArrayOne, *ArrayTwo]};
However when I try to do this, I get an error: Initializer element is not a compile-time constant.
I've read that this is because I'm creating an array with dynamic values, though it should be static. Not sure how to work around this.
Any advice on making an array of array of strings?
Use NSArray, or rather NSMutableArray if you want to modify it after creation:
NSMutableArray *arrayOne = [#[#"hello", #"hi"] mutableCopy];
NSMutableArray *arrayTwo = [#[#"goodbye", #"bye"] mutableCopy];
NSMutableArray *arrayOfArrays = [#[arrayOne, arrayTwo] mutableCopy];
There are other ways to initialise it, but this is the only way that allows you to use Objective-C literal syntax.
You cannot store plain ol' C arrays within an Objective-C collection class as your code attempts to do.
You wrote:
it should be static
if this is what you want then your use of C arrays is quite valid, you just got the syntax wrong. You can use:
NSString *arrayOfArrays[][2] =
{ {#"hello", #"hi"},
{#"goodbye", #"bye"},
};
Important: The 2 is the number of elements in the inner array, you do not change it when adding further pairs.
This will give you a compile-time static array.
If what you are making is a map from one word to another you might be better off with a dictionary, e.g.:
NSDictionary *wordMap =
#{ #"hello" : #"hi",
#"goodbye" : #"bye"
};
and accessing an element becomes:
wordMap[#"hello"];
Note: the dictionary "constant" here is actually executed code; the C array version can appear as a global or local initialiser, while the dictionary initialisation must be done in a method/function - but it can assign to a global.
HTH
NSArray *array = #[
#[[ #"hello", #"hi" ] mutableCopy],
#[[ #"goodbye", #"bye" ] mutableCopy],
];
NSLog(#"%# is short for %#", array[0][1], array[0][0]);
Output: hi is short for hello
I have NSArray of NSDictionaries I need to extract 2 values or remove the values I don't need from the dictionary in the example below I need to remove id and NumberValue. any of you knows how can I do that?
Array: (
{
customerUS= {
DisplayName = "level";
InternalName = "Number 2";
NumberValue = 1;
id = xwrf
},
customerCAN= {
DisplayName = "PurchaseAmount";
InternalName = "Number 1";
NumberValue = 3500;
id = adf;
};
}
)
I'll really appreciate your help.
First thing, You can not remove/insert/update value in (immutable) NSDictionary/NSArray you need to convert NSDictionary/NSArray to (mutable) NSMutableDictionary/NSMutableArray.
such like
NSArray *myArr = ....;
NSMutableArray *newMutableArr = [myArr mutableCopy];
Then you can change in newMutableArr.
Such like
for(int i = 0 ; i < newMutableArr.count ; i ++)
{
[[newMutableArr objectAtIndex:i] removeObjectForKey:#"id"];
[[newMutableArr objectAtIndex:i] removeObjectForKey:#"NumberValue"];
}
EDITED:
Without Use of for loop and removeObjectForKey, if you have array of dictionary and both are mutable then you can also delete a key and its object from all elements of the array like this:
[newMutableArr makeObjectsPerformSelector:#selector(removeObjectForKey:) withObject:#"id"];
[newMutableArr makeObjectsPerformSelector:#selector(removeObjectForKey:) withObject:#"NumberValue"];
I would advice you to read Apple documents.
For modifying any Collection object after it is created, you need the mutable version.
For NSDictionary we have NSMutableDictionary. Read here.
We have a method for removing objects:
- (void)removeObjectForKey:(id)aKey
There are other methods as well. You can easily refer them in the above mentioned documentation.
Find out removeObjectForKey for deleting record from NSMutabledictionary.
removeObjectForKey pass the key value whatever you have like
all this are your key
DisplayName,
InternalName,
NumberValue,
id
do like this
removeObjectForKey:#"id";
First of all you have to convert the array to mutable array and then you can remove the key-value pairs from dictionary.
NSMutableArray *mutableArray = [yourArray mutableCopy];for(int i=0;i<mutableArray.count;i++){ NSMutableDictionary *outerDictionary = [mutableArray objectAtIndex:i]; for(NSString *key in outerDictionary.allKeys){ NSMutableDictionary *innerDictionary = [outerDictionary objectForKey:key]; [innerDictionary removeObjectForKey:#"id"]; [innerDictionary removeObjectForKey:#"NumberValue"]; }
}
I have a NSMutableArray and a NSArray. Both consist of elements that are NSDictionarys themselves.
A sample structure of both is as follows:
NSMutableArray
[
{
objectId = 4274;
name = orange;
price = 45;
status = approved;
},
{
objectId = 9035;
name = apple;
price = 56;
status = approved;
},
{
objectId = 7336;
name = banana;
price = 48;
status = approved;
}
.
.
.
.
]
and NSAraay is
NSArray
[
{
objectId = 4274;
name = orange;
price = 106;
status = not_approved;
},
{
objectId = 5503;
name = apple;
price = 56;
status = approved;
}
]
What I want is to merge these two arrays so that, if any element in NSArray has same objectId as any element in NSMutableArray, element in NSArray should overwrite on element in NSMutableArray.
So in this case final merged array should look like this
MergedArray
[
{
objectId = 4274;
name = orange;
price = 106;
status = not_approved;
},
{
objectId = 9035;
name = apple;
price = 56;
status = approved;
},
{
objectId = 7336;
name = banana;
price = 48;
status = approved;
},
{
objectId = 5503;
name = apple;
price = 56;
status = approved;
}
.
.
.
.
]
Only way to this I know is to iterate through both arrays and merge. Is there any better way? Any help will be greatly appreciated.
EDIT:
Following dasblinkenlights suggestion, I did it following way
-(NSMutableArray*)mergeTwoArray:(NSArray*)array1 :(NSArray*)array2
{
//array1 will overwrite on array2
NSSet* parentSet = [NSSet setWithArray:array2];
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
for (NSDictionary *item in parentSet)
[dict setObject: item forKey: [item objectForKey:#"objectId"]];
NSLog(#"initial dictionary is %#",dict);
for (NSDictionary *item in array1)
[dict setObject: item forKey: [item objectForKey:#"objectId"]];
NSLog(#"final dictionary is %# with all values %#", dict,[dict allValues]);
return [NSMutableArray arrayWithArray:[dict allValues]];
}
Since your objectId value can be used as a unique key, you could potentially create an NSMutableDictionary on the side, populate it with NSDictionary objects from the first array using objectId value as the key, go through the second array, do the overwrites, and finally harvest the values of the resultant NSMutableDictionary into your final output.
Note that this approach might be helpful only if your arrays are relatively long (1000+ items). If you deal with 10..100 items, I wouldn't bother, and code two nested loops as you suggested.
I would recommend iterating through both arrays and merging, but first sort them. Once sorted, you can merge two arrays in O(N) time. For most purposes, this is about as fast as you can get, and it requires very little code.
If they are large enough that the sort is a bottleneck, you could get fancy using an NSSet: put the (elements of the) over-riding array in the set first, and then add the elements of the original array. But you would have to implement an isEqual method for your elements. In this case, it would mean that your elements would no longer be NSDictionary, but rather a class that inherits from NSDictionary but implements the isEqual method to compare the object ID fields.
Because NSSet gives amortized constant time access, this would be faster, if the arrays are large, since there is no sort phase.
I have a NSDictionary loaded from a remote PList.
It contains an array of dictionaries:
(
{
id = "1234";
count = "45";
},
{
id = "244";
count = "89";
},
{
id = "9909";
count = "123";
}
)
How do I get this into an NSArray? I don't want separate arrays for each key.
I just want an NSArray of NSDictionary.
There is probably a simple answer, but this has been bugging me.
Thanks
You say you have a dictionary containing the array. Whatever the key for the array is, just ask do [dictionary objectForKey:theKey], and you'll have the array.
EDIT: From your comments, it sounds like you just have an NSArray which is not in an NSDictionary at all. If so, you already have what you are looking for.
How about:
NSArray *dicts = [NSPropertyListSerialization propertyListWithData:data
options:0
format:NSPropertyListOpenStepFormat
error:NULL];
Note that this is a deprecated plist format (XML or binary format is now preferred).
have u tried [dictionary objectAtIndex:0]objectAtIndex:0]. try iterating over objectAtIndex in the outer loop.
all the best.