I'm currently working on objective c code where I have an array I'm looping through and based on the outcomes I add a value to a key.
However when needed I want to append the values for a specific key but I have absolutely no clue on how to achieve this with objective c.
I have written an solution for this in swift before but I can't seem to figure out how to apply the same thing in objective c. Here is what I currently have
-(void)makeDirectory:(NSArray*)aList {
NSMutableDictionary *dic = [NSMutableDictionary new];
for (NSDictionary *entry in aList) {
NSString *character = #"";
xbmcMovie *movie = [[xbmcMovie alloc] initWithDictionary:entry];
NSString *name = movie.Title.stripSpecialCharacters.stripArticle.stripSpaces.stripNumber;
character = name.character;
if (![dic objectForKey:character]) {
[dic setObject:movie forKey:character];
}
///[dic ]
}
}
Here is what I did in swift 3.0
func makeDictionary(_ libraryArray: [songsClass])->[String: [songsClass]]{
var dic = [String: [songsClass]]()
for entry in libraryArray {
var character: String = ""
var songName = entry.songName.stripSpecialCharacters().stripArticle().stripSpaces().stripNumber()
guard let char = songName.characters.first?.string() else { return [:] }
character = char
if dic[character] == nil {
dic[character] = [songsClass]()
}
dic[character]!.append(entry)
}
return dic
}
So if I have understood this correctly, your value in the dictionary is an array which contains a movie, and you want to add to this array, so what you need to do is:
NSMutableArray *movieArray = [NSMutableArray new];
[movieArray addObject:movie];
if (![dic objectForKey:character]) {
[dic setObject:movieArray forKey:character];
}
//If you want to add to this array again then you can do
[movieArray addObject:anotherMovie];
//Or if you need to retrieve the array again
movieArray = [dic objectForKey:character];
[movieArray addObject:anotherMovie];
Also your code has
character = name.character;
where name is a NSString?
Related
I have an array of values for example a = [1,2,3] and array of dictionaries b =[{2:"a"},{3:"b"},{45:"r"},{16:"a"}]. How can I get values from b which keys match the values in the array. Can someone give me a hint? Thanks.
In objective-c
NSMutableArray *c = [[NSMutableArray alloc] init];
for (NSNumber *i in a) {
BOOL iFound = NO;
for (NSDictionary *dict in b) {
if ((NSNumber *)[[dict allKeys] firstObject] == i) {
iFound = YES;
[c addObject:(NSString *)[[dict allValues] firstObject]];
}
}
if (!iFound) {
[c addObject: [NSNull null]];
}
}
NSLog(#"%#",c);//("<null>",a,b)
In swift
let a = [1,2,3]
let b = [[2:"a"],[3:"b"],[45:"r"],[16:"a"]]
let c = a.map { i in b.first(where: { $0.keys.first == i })?.values.first }
print(c)//[nil, Optional("a"), Optional("b")]
I'm trying to get information out of this Dictionary that was created from a JSON string. The JSON string is returned from the server and is put in a dictionary. That dictionary is passed to myMethod that is suppose to break it down so I can get the information that each record contains.
The "Recordset" is an Array. The Record is also an array of dictionaries.
How do I get to the dictionaries? I keep getting NSDictionaryM objectAtIndex: unrecognized selector sent to instance
Recordset = (
{
Record = (
{
MODMAKlMakeKey = 1112;
MODlModelKey = 1691;
MODvc50Name = "10/12 Series 2";
},
{
MODMAKlMakeKey = 1112;
MODlModelKey = 1687;
MODvc50Name = "10/4";
},
{
MODMAKlMakeKey = 1112;
MODlModelKey = 1686;
MODvc50Name = "10/6";
},
etc .. etc... ( about 100 records )
Here is what I have
- (void) myMethod : (NSDictionary*) dictionary {
//INITIAL
NSArray * arrRecordSet = [dictionary objectForKey:#"Recordset"];
NSArray * arrRecord = [arrRecordSet objectAtIndex:0];
NSDictionary * theRecord = [NSDictionary dictionaryWithObjects:arrRecord forKeys:[arrRecord objectAtIndex:0]];
for (int i = 0; i < arrRecord.count; i++) {
NSLog(#"MODMAKlMakeKey: %#", [theRecord objectForKey:#"MODMAKlMakeKey"]);
}
}
Try this
NSArray * arrRecord = [arrRecordSet objectForKey:#"Record"];
Try to check first if the return of [dictionary objectForKey:#"Recordset"] is really a dictionary or an array.
To do this:
if([[dictionary objectForKey:#"Recordset"] isKindOfClass:[NSArray class]]) {
//object is array
}
else if ([[dictionary objectForKey:#"Recordset"] isKindOfClass:[NSDictionary class]]) {
//object is dictionary
}
I have filled a NSMutableArray with integer and string values from my database.
The problem is that many values were inserted more than once.
Using the following code I remove duplicate objects
for (id object in originalArray) {
if (![singleArray containsObject:object]) {
[singleArray addObject:object];
}
}
Bus this works only if the objects are exactly the same between them.
Is there a way to remove duplicates based on the integer value?
EDIT (from an OP's comment on a deleted answer)
I have some objects containing int and NSString. For example #"John 13", #"Mary 25", #"Luke 25", #"Joan 13". The NSMutableArray will contain all four names and duplicates of 13, 25. I want to remove the duplicates leaving 13 and 25 only once in the array. I do not care which names will be removed. Care only for the integer values to use them later.
If your elements are all NSNumber objects:
for (int i=0;i<array.count;i++) {
for (int j=i+1;j<array.count;j++) {
if ([array[i] isEqualToNumber:array[j]]) {
[array removeObjectAtIndex:j--];
}
}
}
Or if all objects are either integer NSNumbers or NSStrings containing integer values:
for (int i=0;i<array.count;i++) {
for (int j=i+1;j<array.count;j++) {
if ([array[i] intValue] == [array[j] intValue]) {
[array removeObjectAtIndex:j--];
}
}
}
Try this:
// singleArray is initially empty
for (id object in originalArray)
{
BOOL contains= YES;
for( id single in singleArray)
{
if( [single integerValue]==[object integerValue] )
{
contains= NO;
break;
}
}
if(contains)
{
[singleArray addObject: object];
}
}
no test, tell me if it does not work. assuming objects in the array are string and format is "WORD NUMBER"
Boolean myEqual(const void *value1, const void *value2) {
NSString *str1 = (__bridge NSString *)(value1);
NSString *str2 = (__bridge NSString *)(value2);
NSArray *arr1 = [str1 componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSArray *arr2 = [str2 componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
return [[arr1 lastObject] isEqual:[arr2 lastObject]];
}
CFHashCode myHash(const void *value) {
NSString *str1 = (__bridge NSString *)(value);
NSArray *arr1 = [str1 componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
return [[arr1 lastObject] hash];
}
NSMutableArray *array = // your array;
CFSetCallBacks callBacks = kCFTypeSetCallBacks;
callBacks.equal = myEqual;
callBacks.hash = myHash;
CFMutableSetRef set = CFSetCreateMutable(NULL, [array count], &callBacks);
for (id obj in [array copy]) { // copy so can modify the original array
if (CFSetContainsValue(set, (__bridge const void *)(obj))) {
[array removeObject:obj];
} else {
CFSetAddValue(set, (__bridge const void *)(obj));
}
}
I begin in Ios dev and I got some troubles to manipulate an array create by Json :
I call in my app a web Service which return me data :
{evenements =(
({
dateEvenement ={
1 = "01-01-2013";
2 = "02-01-2013";
3 = "03-01-2013";
4 = "04-01-2013";
};
idEvenement = 61;
nbrInvite = 1;
nomEvenement = "My event Name";
nomUtilisateur = "Lucas ";
}
),
);
}
I'm able to get all the values by the following code except for "dateEvenement" :
NSArray *msgList;
msgList = [ jsonResults objectForKey:#"evenements" ];
for (NSDictionary *evenements in msgList) {
for (NSDictionary *evenement in evenements ) {
NSString *idEvenement = [evenement objectForKey:#"idEvenement"];
NSString *nomUtilisateur = [evenement objectForKey:#"nomUtilisateur"];
NSString *nomEvenement = [evenement objectForKey:#"nomEvenement"];
NSString *nbrInvite = [evenement objectForKey:#"nbrInvite"];
NSArray *dates = [ evenement objectForKey:#"dateEvenement" ];
}
}
Can you help me for getting datas of "dateEvenement"
Well in your JSON the dateEvenement isn't an Array but a dictionary:
NSDictionary *dates = [ evenement objectForKey:#"dateEvenement"];
for(NSNumber *key in dates) {
NSString *dateString = [dates objectForKey:key];
NSLog(%# : %#, key, dateString);
}
As declared in your JSON example the key's for the dictionary are numbers, thus you should NSNumber object for the key type.
My json stiring is:
{
"locations" :[
{
id = 0;
lat = "41.653048";
long = "-0.880677";
name = "LIMPIA";
},
{
id = 1;
lat = "41.653048";
long = "-0.890677";
name = "LIMPIA2";
}
]
}
Using:
NSDictionary * root = [datos_string1 JSONValue];
NSArray *bares = (NSArray *) [root objectForKey:#"locations"];
for (NSArray * row in bares) {
NSString *barName1 = [bares valueForKey:#"name"];
NSLog(#"%#",barName1);
}
I obtain from NSlog , twice otput
(
LIMPIA,
LIMPIA2
)
So somthing is wrong. I need to estract di single value parameter (lat, lon and nombre) for each item (in order to use in a mapkit app). Could you help me?
I need to estract di single value parameter (lat, lon and nombre) for each item (in order to use in a mapkit app)
If I understand your question correctly, you're trying to access each value in each dictionary in the locations array, is that right?
In order to access each value (if that is indeed your question), this should work:
NSDictionary *root = [datos_string1 JSONValue];
NSArray *bares = (NSArray *)[root objectForKey:#"locations"];
// Each item in the array is a dictionary, not an NSArray
for (NSDictionary *dict in bares) {
// Loop over keys
for (NSString *key in [dict allKeys]) {
NSLog(#"dict[%#] == %#", key, [dict objectForKey:key]);
}
}