Menu
  • HOME
  • TAGS

Error Store NSdata to NsDictonary

ios,nsdictionary,nsdata

I got the output from your URL and I created the New project and Run , the project link is attach here

Converting String into NSDate in array of dictionaries

arrays,swift,casting,nsdate,nsdictionary

I dont know how you set up things before this little snippet in you question but this is how I did: var arr:[[String:AnyObject]] = [["id":1, "planning_id":2, "started_on":"2015-05-13"], ["id":1, "planning_id":2, "started_on":"2015-05-14"], ["id":1, "planning_id":2, "started_on":"2015-05-10"]] for (i, dict) in enumerate(arr) { let dateString = dict["started_on"] as! String let formatter = NSDateFormatter() formatter.dateFormat...

-[__NSDictionaryI isNSString__]: message sent to deallocated instance

ios,objective-c,nsdictionary,writetofile

First off, thank you all, especially Duncan and Hot Licks for helping me narrow down the bug and finally catching it. So, I noted that an NSDictionary inside my NSArray was being deallocated as soon as I moved out of the scope of viewDidLoad, meaning that I didn't actually own...

Setting an object's properties from an NSDictionary with keys that are not identical to the property names

objective-c,cocoa,cocoa-touch,nsdictionary

No, it is not to rubyish, because Objective-C is dynamically typed. You can do this with key value coding: for (NSString *key in dictionary) { id value = dictionary[key]; [self.configuration setValue:value forKey:key]; } But see my comments here. BTW: If a key does not exist in a dictionary, the result...

Why I receive warning in objectForKey method?

objective-c,nsdictionary,data-type-conversion

Your countRowsInSection: seems to expect its argument to be a long. But you're sending it an object (probably an NSNumber). If that is the case, the following will work: [objectp.methodA countRowsInSection:[[tableSections objectForKey:[NSString stringWithFormat:@"%ld", sect] longValue]]]; ...

Add a permanent NSDictionary to ios app

ios,objective-c,iphone,xcode6,nsdictionary

store your data in archive using NSUserDefault. and Update data after some time period ex. every 2 hour or whatever. Store Data NSData *datadic = [NSKeyedArchiver archivedDataWithRootObject:yourDictionaryName]; [[NSUserDefaults standardUserDefaults] setObject: datadic forKey:SCHEDULEDATA]; [[NSUserDefaults standardUserDefaults] synchronize]; GET Data if([[NSUserDefaults standardUserDefaults] valueForKey:SCHEDULEDATA]!= nil){ NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; NSData *data = [defaults...

Cannot override initializer of NSDictionary in Swift

swift,nsdictionary,swift-extensions

Swift has an official extension mechanism for adding methods to classes, but the compiler kicks up an error when a subclass overrides an extension method. The error text looks hopeful, though (emphasis added): Declarations from extensions cannot be overridden yet It’s that dangling “yet” that encourages me to believe that...

NSDictionary and string literal keys

ios,objective-c,nsstring,nsdictionary,nsmutabledictionary

NSDictionary is a hash table, which means that at first some function is calculated over the key to find the index of value in some array (called hash code, it is a quick operation). Then, since some keys can produce the same hash value, all keys for this hash code...

Adding dictionary in plist file

ios,objective-c,xcode,nsdictionary,plist

First of all copy your plist file at document directory. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); plistPath = [[paths lastObject] stringByAppendingPathComponent:@"organizations.plist"]; if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath]){ NSString *bundle = [[NSBundle mainBundle] pathForResource:@"organizations" ofType:@"plist"]; BOOL sucesss = [[NSFileManager defaultManager] copyItemAtPath:bundle toPath:plistPath error:&error]; if (!sucesss) { NSLog(@"Exception...

get var from an array

ios,objective-c,facebook-graph-api,nsarray,nsdictionary

Try this: NSArray *feed =[result objectForKey:@"data"]; for (NSDictionary *dict in feed) { if ([dict[@"name"] isEqualToString:@"Timeline Photos"]) NSLog(@"%@",dict[@"id"]); } This will only print id when name is equal to Timeline Photos. Actually, you are not working with an array, but with a dictionary. Hope this helps....

Convert this to javascript

javascript,json,swift,nsarray,nsdictionary

let results: NSDictionary = jsonresult["results"] as! NSDictionary var results = jsonresult["results"]; let collection1: NSArray = results["collection1"] as! NSArray var collection1 = results["collection1"]; for item in collection1 { for(var item in collection1){ In JS item will the index. So to access the value from the array you need to access...

Parsing a Dictionary of Arrays from a Plist file

ios,objective-c,nsarray,nsdictionary

Since you already mentioned trying a for loop yourself I don't know if this is actually the kind of answer you are looking for, but for this very specific purpose (i.e. you're certain that the input dictionaries always have the kind of structure you described) something along these lines should...

Loading data from nested NSUSERDEFAULTS into UITABLEVIEW

ios,objective-c,uitableview,nsdictionary,nsuserdefaults

Try this code NSArray *dataArray = [_myDict objectForKey:_keysArray[indexPath.row]]; NSDictionary *data = dataArray[0]; cell.textLabel.text = [data [email protected]"Title"]; _myDict is List dictionary that contains two arrays at 0002 and 0003 so you need to first extract the array then get the first object that is your data. now you can access all...

How to store multiple values for the same key in an NSDictionary, given an NSArray of JSON objects?

ios,objective-c,json,nsarray,nsdictionary

I think you can loop the array and before setValueForKey, you check if the key already exists, if it is yes, and if value for that key is of type NSDictionary, you combine the current one with the existing one as an array, otherwise value for that key should be...

Unwrapping Json Swift (found nil)

json,string,swift,nsdictionary,value

Pictures is in not in the subdictionary your other values are. This should work, but you should check all values if they are nil before you force cast them. if let pictureArray = jsonData["pictures"] as? NSArray { if let pictureDict = pictureArray.firstObject as? NSDictionary { if let pictureName = pictureDict.objectForKey("name")...

How to get a specific object from data structure based on Index

ios,objective-c,nsarray,nsdictionary

Get the keys of the dictionary: NSArray *keys = yourMainDictionary.allKeys; Sort this array by treating the keys as version numbers, since that's what they appear to be (based on your data structure format): NSArray *sortedKeys = [keys sortedArrayUsingComparator:^(NSString *key1, NSString *key2) { return [key1 compare:key2 options:NSNumericSearch]; }]; Iterate over these...

Getting JSON Sub Category Element Issue

ios,nsarray,nsdictionary

( marks the beginning of an NSArray. If you look at the original JSON that would be a [ character. You need to index an array, not access it by key. This means that _dicSubCategory is not a dictionary, regardless of how the variable is declared. The type of the...

How can I correctly set and use a Dictionary?

ios,swift,dictionary,nsdictionary

The issue is with the assignment operator you are using in the following code: self.topStandbyUsers[0] = ["fullname"="My Name","description"="Some description"] Change that to: self.topStandbyUsers[0] = ["fullname":"My Name","description":"Some description"] You can retrieve the value using: var data = self.topStandbyUsers[0]! println(data["fullname"]) ...

Deleting the keys and values in NSDictionaries more than the value 100.000 kilometers

ios,objective-c,nsdictionary

You can filter the dd as below: NSSet *keys = [dd keysOfEntriesPassingTest:^BOOL(NSString *key, NSNumber *obj, BOOL *stop) { return obj.floatValue < 10000; }]; NSLog(@"%@", keys); [keys enumerateObjectsUsingBlock:^(NSString *key, BOOL *stop) { NSLog(@"%@", dd[key]); }]; ...

Custom object to NSMutableDictionary

ios,nsdictionary

You can simply use arrays, dictionaries, strings, numbers, dates (anything which can be written into a plist or JSON). The question is wether this is done solely during 'archiving', or whether your in-memory representation is also arrays and dictionaries. You can also create a custom class which either uses a...

How to invoke block in NSDictionary?

objective-c,nsdictionary,block

You should create a local variable to cast id to block type. void(^block)(void) = [actions objectForKey:@"run"]; if(block) { block(); } ...

Error using `NSDictionary` in swift

ios,swift,nsdictionary

The help says func requestImageForAsset(_ asset: PHAsset!, targetSize targetSize: CGSize, contentMode contentMode: PHImageContentMode, options options: PHImageRequestOptions!, resultHandler resultHandler: ((UIImage!, [NSObject : AnyObject]!) -> Void)!) -> PHImageRequestID and you supply info: NSDictionary! Change it so you supply info: [NSObject : AnyObject]! ...

Send NSString as body of post method using NSURLSession

ios,objective-c,nsstring,nsdictionary,nsurlsession

I ended up using the first example that I found here is my implementation: NSURL *url = [NSURL URLWithString:@"MY_LINK/smtg"]; //Create thhe session with custom configuration NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration]; sessionConfiguration.HTTPAdditionalHeaders = @{ @"Authorization" : [NSString stringWithFormat:@"BEARER %@",finalToken], @"Content-Type" : @"application/json" }; NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration]; // 2...

Error in adding an element to [String:Array] in Swift

ios,arrays,swift,nsdictionary

The problem is probably that you are unwrapping self.model.data[i] when you assign [dict] to it. I assume you are doing that in the case where data[i] has no value yet. So the forced unwrap will result in a nil pointer, which causes a crash. Try this: for var k=0;k<body.count;k++ {...

Need to reload/recalculate NSArray

ios,arrays,database,nsdictionary

You should not store the Opening State. This should be a computed property. Create method that returns this value when requested: - (OpeningState)openingState { OpeningState _openingState; NSDate *openingTimeDate = [timeFormat dateFromString:[currentDay stringByAppendingString:_openingTime]]; NSDate *closingTimeDate = [timeFormat dateFromString:[currentDay stringByAppendingString:_closingTime]]; // Find out opening state of the restaurant if(([openingTimeDate compare:now] == NSOrderedAscending)...

Order an Array/Dictionary in objective c [duplicate]

ios,objective-c,json,uitableview,nsdictionary

Your resultArray contains an array of CoffeeStore objects, which have a distance given to their init method. You need to sort the array based on distance, before you call reloaddata. Hopefully those objects have a distance property and you can sort by that property, like this: NSSortDescriptor *distanceDesc = [NSSortDescriptor...

Not all keys work when converting JSON String to NSDictionary

ios,objective-c,json,nsdictionary,nsdata

After attempting to debug this for several hours, my supervisor and I decided to restart the MacBook I'm developing on. This resolved the runtime issue, and the code in my question is once again working as expected. We are still unsure what caused the device to get into this state,...

Parse Nsmutabledictionary and extract value

ios,objective-c,json,nsdictionary,nsmutabledictionary

You cannot use valueForKey: method for getting corresponding object from an NSDictionary, it should be NSString *id_user = [dictResponce objectForKey:@"@id"];. For getting ann object with valueForKey:, it should be an NSMutableDictionary EDIT: Actual problem is not the valueForKey: method, The bug is in the key, you cannot use a leading...

Get NSString as NSArray from NSDictionary

ios,objective-c,iphone,nsarray,nsdictionary

I didn't find any cocoa method for this task, so I replaced , with & that occurs within {} and then used [string componentsSeparatedByString:@","] method to get it as NSArray. Below is the code -(NSString *)prepareFields:(NSString *)string { NSString *remainingString =string; NSString *newString = @""; @try { while ([remainingString rangeOfString:@"{"].location...

NSDictionary - Parsing item out of a return JSON service

ios,json,nsdictionary

NSDictionary *platesJson = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]; for(id key in platesJson) { id myvalue = [platesJson objectForKey:key]; NSString *myValue = [platesJson objectForKey:key]; } I guess this will work, [platesJson objectForKey:key]Will get value. If the value is a Dictionary,you need to loop in again. But in the image you post, it...

Populating Custom TableViewCell from Twitter using JSON Serialization

objective-c,uitableview,nsdictionary,tableview,nsjsonserialization

You should call [tableView reloadData]; in your request completion handler, after you've filled your array. Check if you receive any data. Does the array get filled with dictionary objects? But mate, seriously, you need to read some good books about coding, your code really lacks understanding of what you're doing....

Return value of object in NSDictionary with several keys

ios,json,nsdictionary

The fastest method might be using NSEnumerator to get the values you want. In the example below you'll see how to enumerate through all keys, and also individual keys: // NSEnumerator id key = nil; NSEnumerator *enumerator = [[json allKeys] objectEnumerator]; while ((key = [enumerator nextObject])) { id object =...

Content of a NSMutableDictionnary erratically returned

cocoa,nsdictionary,nsmutabledictionary

This is a guess: The information supplied does not show that your type myKey implements isEqual: and hash. Keys must implement these methods to work correctly in an NSDictionary; if they are not implemented the default NSObject implementations will be used and they probably do not produce the correct results...

EXC_BAD_ACCESS with NSDictionary/CFDictionaryRef

objective-c,nsdictionary,exc-bad-access

It looks like bad memory management. You call CFRelease on batProps after bridging the pointer to an NSDictionary. This leaves batteryRawDict pointing to garbage. I suggest you change these two lines: batteryRawDict = (__bridge NSDictionary*)batProps; CFRelease(batProps); to: batteryRawDict = (__bridge_transfer NSDictionary *)batProps; If you are using ARC then you are...

Count Parents tag in JSON file iOS

ios,objective-c,json,nsdictionary

NSDictionary has method allKeys NSArray *allKeys = [dictionary allKeys]; for (NSUInteger i = 0; i < allKeys.count; i ++) { NSArray *imagesArray = [dictionary objectForKey:[allKeys objectAtIndex:i]]; //parse your images } Hope this will help you....

Split nsarray to nsdictionary

ios,objective-c,nsarray,nsdictionary

You answered your own question when you say: I want to create a NSdictionary with the districts as a key and the value for that key is an array with the points that are in that district. [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) { if (!error) { NSMutableDictionary *dict = [@{}...

Using map on NSDictionary

swift,closures,nsdictionary

Xcode cannot be trusted with its reasons for an error in Swift, but you can trust it points it out in the right location :) CLLocationCoordinate2dMake() as! Float will create an error. Because you cannot cast a struct to a number. Remove as! Float and your error will go away....

Translate an array of NSdictionnary with NSlocalizedstring

ios,arrays,swift,nsdictionary,nslocalizedstring

You can simply do something like this : let section1 = [NSDictionary(objects: [NSLocalizedString("English base language test", comment:""), 2], forKeys: ["title", "value"]) ] let section2 = [NSDictionary(objects: [NSLocalizedString("English base language test2", comment:""), 2], forKeys: ["title", "value"]) ] and define two Localizable.strings file, one for french and one for english with this...

get array from dictionary from NSMutableArray iOS

objective-c,iphone,ios8,nsmutablearray,nsdictionary

Seems like you didn't ask the question you needed correctly. Based on your question, answer is, just store the object at index of the self.temporaryArray to NSDictionary variable and access it from there using "[ valueForKey:@"options"]"...

How to retrieve specific id from JSON tree

ios,json,nsdictionary

Create a product object with name, image etc as its properties. Then add this object to your array. . . . for (NSDictionary *product in subcategory[@"products"]) { Product *product = [[Product alloc]init]; product.name = product[@"name"]; product.image = product[@"image"]; //and so on [_arraySubCategory addObject:product]; } Now when you want to get...

How to remove NSDictionary while iterating in NSMutableArray [duplicate]

ios,objective-c,nsdictionary,nsmutabledictionary

Try something like this... I assume value for key "name" might be a string. NSSet *set = [NSSet setWithArray:[uniqueArraySort valueForKey:@"name"]]; NSMutableArray *array = [NSMutableArray new]; for (NSString* value in set.allObjects) { NSArray *filteredArray = [uniqueArraySort filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"name = %@", value]]; if(filteredArray.count > 0) [array addObject:[filteredArray firstObject]]; } return array; UPDATE...

File with string in JSON format , how to read filecontent into NSDictionary

ios,json,file,nsdictionary

Get the file's data using NSData's dataWithContentsOfFile method (the file path should be the path to the file in the bundle; there is a method that can get you the path of a resource from the app main bundle). Then use NSJSONSerialization's JSONObjectWithData method to create a NSDictionary from the...

Cannot subscript a value of a type AnyObject, in Swift

json,swift,nsdictionary

In your edit it looks like you're using SwiftyJSON. If that is indeed the case, you can help the compiler to know what's in the dictionary by using SwiftyJSON's dictionaryValue property: let jParams = jdata["responseData"]["extraData"]["params"].dictionaryValue Then you should be able to access your values without downcasting: let title = jParams["title"]...

Searching an Array of Strings in Array of Dictionaries

ios,objective-c,nsarray,nsdictionary,nspredicate

It might be helpful to use (NSPredicate*)predicateWithBlock: method to speed up searching. Suppose you have a keys array and a source array, you want to filter the source array with the keys array. NSArray *keysArray = @[@"1",@"2",@"3"]; NSArray *sourceArray = @[@"12",@"2",@"3",@"1",@"2"]; For the first object @"12" in sourceArray, looking at...

Update/change values of NSDictionary keys stored in NSArray

objective-c,nsarray,nsdictionary,segue,nspredicate

You may only change the values for key in mutable subclasses of NSDictionary, NSDictionary itself is immutable. so since you have changed to a mutable array, you can do the same thing for each of the dictionaries also: filteredClientArray = [NSMutableArray arrayWithArray:sortedArray]; for(NSDictionary *d in [filteredClientArray copy]) { NSMutableDictionary *...

Given a dictionary of numbers, determine which sets contain unique values (i.e. numbers that do not belong to any of the other sets)

ios,objective-c,nsdictionary,unique

Extract the values (as an array, [dict allValues]) and coerce to an NSSet (initWithArray:). You can always coerce back to an array if you really do want an array; but I find in general that often people think they need an array when what they really needed was a set...

Convert String(already formatted) to an Array of NSDictionary

ios,arrays,string,nsdictionary

Your formatted string must be well formatted as an json, then you can use the next code: NSString* [email protected]"[ {\"name\": \"Laura\", \"age\":33, \"gender\": \"female\"}, {\"name\": \"James\", \"age\":25, \"gender\":\"male\"} ]"; NSData* data=[str dataUsingEncoding:NSUTF8StringEncoding]; NSArray* jsonArr=[NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; NSLog(@"%@",jsonArr); ...

Set Selected Second component in UIPickerView to a NSString [closed]

ios,objective-c,nsdictionary,uipickerview

You probably want: rowSelection2 = [secondComponent objectAtIndex:row]; since it is your secondComponent array that contains the current contents for the 2nd component of the picker view. This assumes that you populate the 2nd picker component with your secondComponent ivar. You have a few other issues. Change the method to this:...

How to parse XML from web services into NSArray in Objective-C

ios,objective-c,xml,nsdictionary,nsxmlparser

You could use the NSXMLParser to do this. Here is a sample code. NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://myIP/Services.asmx/GetDetails?CId=02&SId=01"]]; NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:url]; parser.delegate = self; [parser parse]; -(void)parser:(NSXMLParser*)parser didStartElement:(NSString*)elementName namespaceURI:(NSString*)namespaceURI qualifiedName:(NSString*)qualifiedName attributes:(NSDictionary*)attributeDict { //Use attributeDict to get parsed XML into...

How initWithObjectAndkeys using variable in iOS

ios,objective-c,json,xcode6,nsdictionary

Your saved result is NSArray ie arrResult , so we will loop through it. for(NSDictionary *dictObject in arrResult) { //Get Data Dictionary NSDictionary *dictData = [dictObject valueForKey:@"data"]; //Now have data so traverse for (NSString*strkey in dictData) { id value = [dictData objectForKey:strkey]; NSLog(@"id = %@",value); } } ...

Extracting usable data from an API response in Swift

json,swift,nsdictionary

You are missing the code needed to load the JSON file and parse it. Also, the JSON you have posted has some illegal characters which will choke the parser. e.g.: { “Green Shirt": [ The first quote is a curly quote. First, you need to clean all of these up....

NSPredicate filtering an array based on a localised string entry

ios,nsarray,nsdictionary,nspredicate,nslocalizedstring

I think your problem is in the %K.%@, if you look at the final predicate I believe that it will put quotes around the %@, which is not what you want (guessing by the dot notation). EDIT: You could also use a predicate block: NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject,...

Error tells me that my textview is nil when trying to make NSDictionary

ios,objective-c,xcode,constraints,nsdictionary

The mistake you're making is that viewWithTag: doesn't instantiate a new UIView, it just searches an existing UIView's heirarchy for another UIView that has that as its tag value. More at the documentation: https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIView_Class/index.html#//apple_ref/occ/instm/UIView/viewWithTag: What you need to do is instatiate your UIView first, then set its tag: UIView *infoView...

JSON: Understanding format in Objective-C

objective-c,json,nsdictionary

First, your json as given is not valid son :( you have a quote to many. If we escape it like this: {"keyA":{"lon":139,"lat":35},"keyB":[{"key1":"value\" clouds","key2":"023"}]} Then, it's ok. Now, what you have here is an son object, containing 2 keys (A and B). And KeyB is associated with a json Array...

Convert NSDictionary to NSArray

ios,objective-c,uitableview,nsarray,nsdictionary

I believe if you would extract allValues instead of allKeys then you could only: [values objectAtIndex:indexPath.row] Since you are using a index as indexPath.row. Let me know if this helps....

Filling an array with NSDictionary

ios,objective-c,uitableview,nsdictionary

Normally as per you say you have Array of Dictionaries. So you should follow these steps to fetch data. Step 1. self.dataDictArray = (NSArray*)responseObject; Step 2. self.dataDict=[self.dataDictArray objectAtIndex:0]; Step 3. NSLog(@"ID = %@",[self.dataDict valueForKey:@"id"]); Simple. Cheers....

Why my NSDictionary that was from json sorted like this?

ios,json,swift,sorting,nsdictionary

NSDictionary always has no order. If you enumerate or print it, it will appear in basically random order. If you want to have it ordered, you'll have to get the keys and values and sort them yourself, or use something other than an NSDictionary.

how to retrive JSON data by using swift

json,swift,nsdictionary

Your data structure does not begin with an array this time, but with a Dictionary. Your structure is like is: root Dictionary -> "salutation" -> Dictionary root Dictionary -> "station" -> Dictionary root Dictionary -> "subDivsion" -> Dictionary Let's say you want to access the "id" of "salutation", then: //...

Parsing Json Output correctly

ios,objective-c,json,nsdictionary

You can create an easier dictionary: NSArray *chat = array[@"chat"][0]; NSMutableDictionary* newDict = [NSMutableDictionary dictionary]; for (NSDictionary* d in chat) [newDict setValue:d[@"Value"][@"Value"] forKey:d[@"Key"]]; Now you can use the newDict. NSLog(@"chatId: %@", [newDict valueForKey:@"chatId"]); ...

Parsing JSON into a usable format

swift,nsarray,nsdictionary,nsurl

The trick is to declare the right type for the cast. For your data we are using [String: [[String: AnyObject]]]: a dictionary with a String as key and an array of dictionaries as value, these dictionaries have their value as AnyObject because there's several possible types. After a successful decoding,...

Why should I not be using [NSDictionary objectForKey:]?

objective-c,nsdictionary

There is no performance difference, just that the literal syntax is more clear, less verbose and has been available for several years now. If the current code is like: id var = [dictionary objectForKey:@"key"]; replace it with: id var = dictionary[@"key"]; ...

get const char from nsdictionary

ios,objective-c,char,nsdictionary

You pass const char as type, while the reference to input data is of type const char *. const char * is used for C strings or binary dara. In the first case you should convert it to an instance of NSString. But in your case it is obviously used...

Simple Way to Access Within JSON NSDictionary Object Values in Swift?

ios,json,xcode,swift,nsdictionary

You should probably use https://github.com/SwiftyJSON/SwiftyJSON. It handles most of the cases that you want to handle.

Sort NSArray by other NSMutableDictionary

ios,objective-c,uitableview,nsdictionary,nssortdescriptor

The NSArray method sortedArrayUsingComparator: takes a block that compares two objects. You can write that block any way you want, including using a dictionary to look up the sort values for each element in the array. If your sortValue dictionary is changing on a different thread then you'll need to...

In Swift, what is the effect of having a Type Declaration after the colon? [duplicate]

swift,syntax,casting,nsdictionary

In the second case, you're explicitly defining the type for temp2, saying it's an NSDictionary. In the first case, you're letting the compiler infer it's an NSDictionary. In your specific example, there's no difference. However, if you do something like this: var temp1 = NSArray() var temp2: NSDictionary = NSArray()...

how to search and replace in NSDictionary?

ios,objective-c,nsdictionary

Consider your input dictionary as mainDictionary and use following code: NSMutableDictionary *valuesDic = [mainDictionary objectForKey:@"VALUES"]; NSArray *allPossibleKeysArray = [valuesDic allKeys]; for (int j=0; j<allPossibleKeysArray.count; j++) { NSString *keyStr = [allPossibleKeysArray objectAtIndex:j]; NSArray *array = [valuesDic objectForKey:keyStr]; for (int i=0; i<array.count; i++) { NSMutableDictionary *dictionary = [array objectAtIndex:i]; NSString *keyString =...

Apple watch communicate with iOS app a new swift project vs to existing obj c project

objective-c,swift,nsdictionary,apple-watch

Solved it! Missed out the reply(aNsdictionary) in the app delegate...

How to get the same data like json in NSDictionary

json,swift,nsdictionary

If order is important you cannot rely on an NSDictionary because its keys are arbitrary. To solve this ordering problem you would want to use an array instead. So change you json structure to: { "data":[ {"0":["All Venues"]}, {"1_190":["AEP Gifu"]}, {"2_69":["ARAI Bayside"]} ] } And when converted you will have...

Access data from NSDictionary

ios,json,swift,nsdictionary

Your json is not an array of Dictionaries, it is just a Dictionary. Change [[String: AnyObject]] to [String: AnyObject] and it will work....

NSDictionary returning an optional integer when retrieving information

swift,dictionary,int,type-conversion,nsdictionary

The Optional(1) value just means that the value is an optional swift type. You can unwrap the value from an optional using the ! operator. let a = friendLetterCount["a"]! as Int println(a) a will the unwrapped value. You can also use optional binding to check for nil while also doing...

Getting error related to NSDictionary object type

ios,objective-c,nsarray,nsdictionary,nspredicate

Your predicate requires two parameters but you only pass 1, it should be NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(SELF.CountryName BEGINSWITH[cd] %@) OR (SELF.ISDCode BEGINSWITH[cd] %@)", searchText, searchText]; By only supplying 1 parameter random memory was taken for the second and in this case turned out to be a view controller....

Obj-C setValuesForKeysWithDictionary 64-bit vs 32-bit

ios,objective-c,json,nsdictionary,32bit-64bit

NSDictionary objects are unordered collections, so code should never make assumptions about the order in which a dictionary will enumerate its own keys. It turns out that there are implementation differences between the 32- and 64-bit runtimes that affect where hashed values end up being stored. Since the API contract...

Compare two arrays of dictionaries and add/remove items

ios,objective-c,nsarray,nsdictionary

I think a loop would do this. for(int x=0;x<[arrUpdate count];x++){ //condition 2 if([[arrCurrent valueForKey:@"id"] containsObject:[[arrUpdate objectAtIndex:x] valueForKey:@"id"]]){ } //condition 1 else{ [arrCurrent addObject: [arrUpdate objectAtIndex:x]] } } Though you could also use predicate. I haven't tested this code for i do not have a machine. But you could at least...

Traversing a dictionary in swift

json,swift,nsdictionary,xcode6.1

Imagine this is my local json file : Json File : { "temp" : [ { "key1": "value1", "key2": "value2", "key3": "value3" }, { "key1": "value1", "key2": "value2", "key3": "value3" }, { "key1": "value1", "key2": "value2", "key3": "value3" } ] } Code to parse JSON and print value of "key2"...

NSDictionary and UITableView subtitle

ios,objective-c,uitableview,nsdictionary,subtitle

In your case, there are 4 sections: "A", "B", "E", and "Y". And each section has only 1 row. So, I assume your cell.detailTextLabel.text = [subtitles objectAtIndex:indexPath.row]; keep getting "Seslendiren: Mustafa Sandal" value? Try change the line to cell.detailTextLabel.text = [subtitles objectAtIndex:indexPath.section]; to see if the problem is solved. Edit:...

How to efficiently loop through multiple nested NSDictionaries and compare values?

objective-c,xml,nsdictionary

First tip: Refactor your data so that this isn't such a difficult operation! If that's not possible there's a few things you can try. Rather than a "for loop", use: [arrStation enumerateObjectsWithOptions: NSEnumerationConcurrent usingBlock: ^(NSDictionary *aPage, NSUInteger idx, BOOL *stop) { // Code here for compare }]; That may perform...

“Extra argument 'foo' in call” OR “'[NSObject : AnyObject]!' is not a subtype of 'Dictionary'”

objective-c,swift,nsdictionary

The problem lies with the closure argument. If you make the parameters match exactly, it works: GenericWebService.get("", params: ["foo":"bar"]) { (responseDictionary: [NSObject:AnyObject]!, connectionError: NSError!) -> Void in // foo } But rather than explicitly type them, it may be easier just to leave Swift to do it for you: GenericWebService.get("",...

ios issue with NSDictionary retrieving value from key

ios,objective-c,nsdictionary

That's because the dictionary contains an NSNumber. Do this: NSNumber *value = [JSON objectForKey:@"backseatBucks"]; ...

Create NSDictionary from Dictionary Log printed by Xcode

ios,objective-c,nsdictionary,nsmutabledictionary

No way whatsoever. The output of NSLog is purely for debugging purposes. You have no chance in hell reconstructing a dictionary from this. Don't even try. What are you actually trying to achieve?...

NSMutableArray adds same NSDictionary multiple times

ios,objective-c,for-loop,nsarray,nsdictionary

You need to alloc and init the array each time, so that there is new memory for it and then it wont add the same array 8 times

Swift: How to make a selected cell NSLog the corresponding value and key from a dictionary

swift,nsdictionary,tableview

So, ideally, you want to use the index path that the method provides to grab whatever cell was selected. Once you have that, you can extract the text from the cell and check with the dictionary. override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { // Lots of optional chaining to...

Retrive specific JSON key from subcategory

ios,json,nsarray,nsdictionary

I'm really not sure specifically what you're asking. It looks like you only want to print out the values from within Coffees. Just skip categories and subcategories that don't match the criteria you want by using if (...) continue;. for (NSDictionary *dict in [_dic objectForKey:@"categories"]) { if (![dict[@"name"] isEqualToString:@"Drink"]) continue;...

How to restructure object of NSDictionaries

ios,objective-c,nsdictionary

this is a simple NSArray which contains objects of type named lean. you can get the needed object by its index UPDATE: I can't be sure of course. I have no idea about lean's structure. But most likely it contains field (and I assume it must be a property) named...

Error when extracting Json data

json,swift,nsdictionary

Note that jsonDict is an NSDictionary. When you iterate over a dictionary, you get a tuple containing (key, value). In this line of code: var obj = item as NSDictionary you are attempting to cast a (key, value) tuple to an NSDictionary which is what is producing the error....

How to downcast to [String: String] in a for in loop?

ios,json,swift,casting,nsdictionary

The cast acts upon promos and not i in this case. Since promos is an array of [String: String] dictionaries, you need to cast promos to [[String: String]]. When you do this, i will have the type [String: String] since it is one element of the [[String: String]] array. for...

Xcode Duplicate NSDictionary

ios,objective-c,xcode,dictionary,nsdictionary

The problem here is that a dictionary only keeps references to the contained objects. When you copy a dictionary, you are only copying the reference, not the objects. So, if you modify something inside one dictionary, you'll see it modified in the other. The solution would be to deep-copy the...

How to iterate concisely through @properties on an NSObject subclass to set properties from a plist?

cocoa,nsarray,nsdictionary,plist,nsobject

Your code example is messed up, but what you want is something like: [new setValuesForKeysWithDictionary:dict]; ...

Swift: Parsing Json string and populating information into a dictionary

json,swift,nsstring,nsdictionary

You can pull those "id" and "title" key-values out using something similar to what I have below. At the end of this routine, all of your data sits in an array of dictionaries, newArrayofDicts. Basically you just generate an array of dictionaries using NSJSONSerialization.JSONObjectWithData, and then hop into each dictionary...

0 randomly becomes 55?

objective-c,swift,integer,nsdictionary

If the dictionary is passed to Objective-C, all the integers will become NSNumber instances. NSDictionary/NSArray cannot hold primitive values. That means you will have to call integerValue on the number, not cast it blindly to int. Or just print it using: NSLog(@"%@", theThreeNotes[@"0"][0]) ...

Storing dictionaries into Firebase?

ios,swift,firebase,nsdictionary

There is nothing wrong with your code. The issue is the values that are being loaded into var currentUserFirstName: String! var currentUserLastName: String! As a test, I created a sample project with the following code, which is a duplicate of your posted code but with normal strings loaded into the...

Swift Dictionary confusion

swift,nsdictionary

dict["list"]![1]! returns an object that is not known yet (AnyObject) and without the proper cast the compiler cannot know that the returned object is a dictionary In your first example you properly cast the returned value to a dictionary and only then you can extract the value you expect....

Calling a specific data key value from NSDictionary Issue

ios,swift,nsarray,nsdictionary

I'm not sure what you're trying to do, but I can tell you why your code is wrong. Here, you assign the values of your dic11 as NSMutableString objects: symbolStr = attributeDict["symbol"]! as NSMutableString offerlStr = attributeDict["offer"]! as NSMutableString dic1 = ["symbolName":symbolStr , "offerAmount":offerlStr] Later, you attempt to access .indexPath...

NSDictionary in NSMutableArray ios

ios,objective-c,nsmutablearray,nsdictionary,nsmutabledictionary

NSString* singleObjectTemplate = [NSString stringWithFormat:@"{\"user\" : \"%@\",\"friend\" : \"%@\"}", user, friend]; NSString* validJsonTemplate = [NSString stringWithFormat:@"{\"A\":[%@]}", singleObjectTemplate]; Something like this. You can modify it as per your requirement to add multiple entries. I hope this helps you in some way. Cheers!! :) EDIT: Suppose you want to add 3 objects...

How to access the next key in a Swift dictionary?

swift,dictionary,nsdictionary

There is no such thing as "the next key"; dictionaries have no order. Since, however, you are iterating through the dictionary... for (k, v) in myDict { println(k) } I'm going to assume that what you mean is: how can I know, on this iteration, what k would be on...

JSON Parsing : Retrieving data from the NSDictionary and storing it in an array

ios,json,parsing,nsdictionary

NSMutableArray *resultArray = [NSMutableArray new]; NSError *jsonError = [[NSError alloc] init]; NSDictionary *pR = [NSJSONSerialization JSONObjectWithData:yourJsonObject options:NSJSONReadingAllowFragments error:&jsonError]; NSArray *pArray = pR[@"Address"]; for(NSDictionary *dict in pR) { [resultArray addObject:dict[@"address"]]; } ...