Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Simulated
Sep 28, 2001
Lowtax giveth, and Lowtax taketh away.
College Slice

bumnuts posted:

I can't POST because its a URL scheme. I'm not even sure if an arbitrary limit would even apply since it doesn't really hit Mobile Safari or ever leave the device.

Every webserver and http library I've come across has some sort of build-in limit... Or at least all the ones I knew about. Proxy servers and URL filters often have limits too. I'm surprised you are getting 400k across a URL since that is entirely in the Get HTTP verb line so the webserver can't check authentication, process headers, or really do anything whatsoever until it loads and parses the entire URL into memory.

Adbot
ADBOT LOVES YOU

pokeyman
Nov 26, 2006

That elephant ate my entire platoon.
bumnuts isn't hitting a web server at all, and iOS only needs to parse the scheme to determine which app to open. So I'm guessing there's a hypothetical limit but it could well be in the megabytes.

duck monster
Dec 15, 2004

I want to travel to california to stab the apple engineer who thought that it would be a good idea to make NSArray and NSDictionary non-mutable. Why the gently caress would such a thing ever exist. Was Steve jobs flipping furniture around that day and decided to order his coders to "be cunts to developers".

I need to drink because this project just got unexpectedly really hard, 2 days after completion deadline.

superh
Oct 10, 2007

Touching every treasure

duck monster posted:

I want to travel to california to stab the apple engineer who thought that it would be a good idea to make NSArray and NSDictionary non-mutable. Why the gently caress would such a thing ever exist. Was Steve jobs flipping furniture around that day and decided to order his coders to "be cunts to developers".

I need to drink because this project just got unexpectedly really hard, 2 days after completion deadline.

What's wrong with NSMutableArray and NSMutableDictionary? And if you've got a lot of NSArrays already, find + replace? Am I missing something?

pokeyman
Nov 26, 2006

That elephant ate my entire platoon.
And there's NSMutableCopying. And if you have an array of arrays or whatever, use -valueForKey: or write a -map: implementation in a category or grab any of the ten million existing reimplementations of ruby's Enumerable module or really I'm not sure what you're complaining about.

duck monster
Dec 15, 2004

superh posted:

What's wrong with NSMutableArray and NSMutableDictionary? And if you've got a lot of NSArrays already, find + replace? Am I missing something?

I've did a search and replace on every instance , and its still bitching me out. :sigh:

duck monster
Dec 15, 2004

E: bah. Forget it.

dizzywhip
Dec 23, 2005

What errors is it giving you?

lord funk
Feb 16, 2004

Did you remember to change them in your .h files as well?

duck monster
Dec 15, 2004

Yes.

Basically what I'm doing is pulling a structure out of a web server using CJSON (Touchjson or whatever) and saving it in the root, uh app delegate thingo, pulling some variables out to display, letting the user gently caress with the variables, and then trying to modify the structure so I can re-serialize it and send it back. Business app on a very short contract.

It appears my cunning plan has hit the rocks :(

I modified all instances on NSDictionary and NSArray to NSMutabledictionary and NSMutablearray or whatever it is, including in touchjson, but its still acting like a total shitbag.

Is there some sort of mutable deep copy I could use, since i think the problem is that this structure is just not producing mutable members of the dictionary.

I'm honestly mystified why they didnt implement dictionaries so that there was an option to be mutable or non mutable, rather than two separate subtly incompatible objects with a preference for the non-useful variant.

ManicJason
Oct 27, 2003

He doesn't really stop the puck, but he scares the hell out of the other team.
edit: I think I misread your question

Doc Block
Apr 15, 2003
Fun Shoe

duck monster posted:

Yes.

Basically what I'm doing is pulling a structure out of a web server using CJSON (Touchjson or whatever) and saving it in the root, uh app delegate thingo, pulling some variables out to display, letting the user gently caress with the variables, and then trying to modify the structure so I can re-serialize it and send it back. Business app on a very short contract.

It appears my cunning plan has hit the rocks :(

I modified all instances on NSDictionary and NSArray to NSMutabledictionary and NSMutablearray or whatever it is, including in touchjson, but its still acting like a total shitbag.

Is there some sort of mutable deep copy I could use, since i think the problem is that this structure is just not producing mutable members of the dictionary.

I'm honestly mystified why they didnt implement dictionaries so that there was an option to be mutable or non mutable, rather than two separate subtly incompatible objects with a preference for the non-useful variant.

70% of the time I'm using an NSDictionary or an NSArray I'm using the immutable versions, for what it's worth. Also, if I'm not mistaken, the immutable versions of the container classes are faster.

Are you just casting them to mutable versions? Because that won't work, use -mutableCopy. You might have to do a deep mutable copy, because if you have an NSArray of NSDictionaries (or vice versa) and call -mutableCopy on the NSArray, all you'll get back is an NSMutableArray full of NSDictionaries.

edit: the book Beginning iOS Development has a section about doing deep mutable copies somewhere in the UITableView chapters. I'll see if I can dig it up.

edit 2: basically, you just create a category on whatever container classes you want that recursively goes through and makes a deep mutable copy instead of a shallow mutable one, like this:

NSDictionary+MutableDeepCopy.h
code:

#import <Foundation/Foundation.h>

@interface NSDictionary (MutableDeepCopy)
- (NSMutableDictionary)mutableDeepCopy;
@end
NSDictionary+MutableDeepCopy.m
code:

#import "NSDictionary+MutableDeepCopy.h"

@implementation NSDictionary (MutableDeepCopy)

- (NSMutableDictionary *)mutableDeepCopy
{
	NSMutableDictionary *returnDict = [[NSMutableDictionary alloc] initWithCapacity:[self count]];
	
	NSArray *keys = [self allKeys];
	
	for(id key in keys) {
		id oneValue = [self valueForKey:key];
		id oneCopy = nil;
		
		if([oneValue respondsToSelector:@selector(mutableDeepCopy)]) {
			oneCopy = [oneValue mutableDeepCopy];
		} else if([oneValue respondsToSelector:@selector(mutableCopy)]) {
			oneCopy = [oneValue mutableCopy];
		}
		
		if(oneCopy == nil) {
			oneCopy = [oneValue copy];
		}
		
		[returnDict setValue:oneCopy forKey:key];
		[oneCopy release];
	}
	
	return returnDict;
}

@end
edit 3: this is from the version of the book that covers iOS 4.x, and I have no idea how well it actually works.

Doc Block fucked around with this message at 06:34 on Feb 26, 2012

duck monster
Dec 15, 2004

Would sticking a category on NSDictionary carry across onto NSMutableDictionary?

Simulated
Sep 28, 2001
Lowtax giveth, and Lowtax taketh away.
College Slice
Are you a loving cave man? Use restkit and let it parse the JSON for you. Send me a PM if you need help figuring it out. I literally just wrote code that does what you are trying to do today.

Eg for a non-mapped object: [XClient post:url parameters:myDictionary delegate:self]. But the awesome bit is if you can just create a class that mirrors your JSON, then you can serialize/deserialize and work with the object directly instead of dictionaries.

If you are having this much trouble or loving around with NSArray vs NSMutableArray you are doing it wrong.

dizzywhip
Dec 23, 2005

duck monster posted:

Yes.

Basically what I'm doing is pulling a structure out of a web server using CJSON (Touchjson or whatever) and saving it in the root, uh app delegate thingo, pulling some variables out to display, letting the user gently caress with the variables, and then trying to modify the structure so I can re-serialize it and send it back. Business app on a very short contract.

It appears my cunning plan has hit the rocks :(

I modified all instances on NSDictionary and NSArray to NSMutabledictionary and NSMutablearray or whatever it is, including in touchjson, but its still acting like a total shitbag.

Is there some sort of mutable deep copy I could use, since i think the problem is that this structure is just not producing mutable members of the dictionary.

I'm honestly mystified why they didnt implement dictionaries so that there was an option to be mutable or non mutable, rather than two separate subtly incompatible objects with a preference for the non-useful variant.

Keep in mind that the mutability of the array or dictionary doesn't have anything to do with the mutability of the objects inside of it. When you say it's "not producing mutable members of the dictionary" it sounds like you're actually trying to modify the objects in the containers rather than the containers themselves. Since the data came from JSON I assume those values are NSStrings or NSNumbers, both of which are also immutable. So even if you put all of those objects into mutable containers, in order to change their values you're going to have to replace those immutable strings and numbers with new objects.

I think the "proper" way to handle this sort of situation is to have some model classes that conform to the type of data you're getting back from the server. They can implement an initWithJson: method that takes in the raw objects and stores them however you want, probably in a mutable format.

Also, [NSMutableDictionary dictionaryWithDictionary: dictionary] and [NSMutableArray arrayWithArray: array] might be helpful to you.

duck monster posted:

Would sticking a category on NSDictionary carry across onto NSMutableDictionary?

I'm not 100% positive but I would assume so since NSMutableDictionary inherits NSDictionary.

lord funk
Feb 16, 2004

Since we're on the topic of restkit, is there a particular tutorial or site anyone can recommend for a first-time user? Any tips that come to mind? I'm just about to implement it.

Simulated
Sep 28, 2001
Lowtax giveth, and Lowtax taketh away.
College Slice
I will try to post something later tonight, I'm too tired to think straight right now. There are existing tutorials but it is actually in flux right now so the docs are in various stages of out-of-date. The good news is the new stuff should eliminate a ton of boilerplate code.

Doc Block
Apr 15, 2003
Fun Shoe
A submission question:
I submitted an app, it's been in Waiting For Review status for a about a week. Last night I discovered stupid bug that was somehow missed in testing, rejected the binary, fixed the bug, and re-uploaded the binary. The app is now back to Waiting For Review.

So my question, for those with more App Store submission/review process experience than me: what are the odds that my app did or didn't get bumped to the back of the Waiting For Review line?

It was originally set to be released on March 1st, but hopefully now it'll at least be approved before Apple's big March 7th event.

eeenmachine
Feb 2, 2004

BUY MORE CRABS

Doc Block posted:

A submission question:
I submitted an app, it's been in Waiting For Review status for a about a week. Last night I discovered stupid bug that was somehow missed in testing, rejected the binary, fixed the bug, and re-uploaded the binary. The app is now back to Waiting For Review.

So my question, for those with more App Store submission/review process experience than me: what are the odds that my app did or didn't get bumped to the back of the Waiting For Review line?

It was originally set to be released on March 1st, but hopefully now it'll at least be approved before Apple's big March 7th event.

You get bumped back to the beginning.

Doc Block
Apr 15, 2003
Fun Shoe
Yeah, figured as much. Guess I was just hoping that wasn't the case.

duck monster
Dec 15, 2004

Gordon Cole posted:

Keep in mind that the mutability of the array or dictionary doesn't have anything to do with the mutability of the objects inside of it. When you say it's "not producing mutable members of the dictionary" it sounds like you're actually trying to modify the objects in the containers rather than the containers themselves. Since the data came from JSON I assume those values are NSStrings or NSNumbers, both of which are also immutable. So even if you put all of those objects into mutable containers, in order to change their values you're going to have to replace those immutable strings and numbers with new objects.

I think the "proper" way to handle this sort of situation is to have some model classes that conform to the type of data you're getting back from the server. They can implement an initWithJson: method that takes in the raw objects and stores them however you want, probably in a mutable format.

Also, [NSMutableDictionary dictionaryWithDictionary: dictionary] and [NSMutableArray arrayWithArray: array] might be helpful to you.


I'm not 100% positive but I would assume so since NSMutableDictionary inherits NSDictionary.

The structure unfortunately is outside of my control, and its a riduculously huge and complex JSON structure. I abandoned modelling it with coredata after realising I'd be at it for weeks and have about 30-40 models in a stupidly complex nest of relations. Not being my system, its outside of my control.

I've replaced all instances of NSDictionary and NSArray in the CJSON library, but it still seems to be producing immutable dictionaries SOMEHOW. :(

Doc Block
Apr 15, 2003
Fun Shoe
Dude. Dude.

You're doing it wrong.

Even if you have no control over the JSON structure, doing a search/replace for NSDictionary and NSArray in CJSON isn't the answer.

With something as complex as you're describing, dictionaries and arrays should be underlying implementation details of your object classes, not the object classes themselves.

duck monster
Dec 15, 2004

Doc Block posted:

70% of the time I'm using an NSDictionary or an NSArray I'm using the immutable versions, for what it's worth. Also, if I'm not mistaken, the immutable versions of the container classes are faster.

Are you just casting them to mutable versions? Because that won't work, use -mutableCopy. You might have to do a deep mutable copy, because if you have an NSArray of NSDictionaries (or vice versa) and call -mutableCopy on the NSArray, all you'll get back is an NSMutableArray full of NSDictionaries.

edit: the book Beginning iOS Development has a section about doing deep mutable copies somewhere in the UITableView chapters. I'll see if I can dig it up.

edit 2: basically, you just create a category on whatever container classes you want that recursively goes through and makes a deep mutable copy instead of a shallow mutable one, like this:

NSDictionary+MutableDeepCopy.h
code:

#import <Foundation/Foundation.h>

@interface NSDictionary (MutableDeepCopy)
- (NSMutableDictionary)mutableDeepCopy;
@end
NSDictionary+MutableDeepCopy.m
code:

#import "NSDictionary+MutableDeepCopy.h"

@implementation NSDictionary (MutableDeepCopy)

- (NSMutableDictionary *)mutableDeepCopy
{
	NSMutableDictionary *returnDict = [[NSMutableDictionary alloc] initWithCapacity:[self count]];
	
	NSArray *keys = [self allKeys];
	
	for(id key in keys) {
		id oneValue = [self valueForKey:key];
		id oneCopy = nil;
		
		if([oneValue respondsToSelector:@selector(mutableDeepCopy)]) {
			oneCopy = [oneValue mutableDeepCopy];
		} else if([oneValue respondsToSelector:@selector(mutableCopy)]) {
			oneCopy = [oneValue mutableCopy];
		}
		
		if(oneCopy == nil) {
			oneCopy = [oneValue copy];
		}
		
		[returnDict setValue:oneCopy forKey:key];
		[oneCopy release];
	}
	
	return returnDict;
}

@end
edit 3: this is from the version of the book that covers iOS 4.x, and I have no idea how well it actually works.

Doesnt work. Shits itself complaining that NSCopying does have a copy with zone.

This however does work:

http://www.mlsite.net/blog/?p=213

Very well actually.

Now. What actually is Copy with zone, for curiosity sake.

Doc Block
Apr 15, 2003
Fun Shoe
Yeah, I've never actually used that code and just copied it straight out of the book.

I'd still prefer having the check to see if the object actually responds to mutableDeepCopy and if not then failing over to mutableCopy and then copy, so it won't crash when it gets to an object without a deep copy category added to it.

duck monster
Dec 15, 2004

Doc Block posted:

Yeah, I've never actually used that code and just copied it straight out of the book.

I'd still prefer having the check to see if the object actually responds to mutableDeepCopy and if not then failing over to mutableCopy and then copy, so it won't crash when it gets to an object without a deep copy category added to it.

The code you posted does check , and NSNumber supports mutableCopy, or at least the protocol but seems to actually poo poo itself on it. Or at least on the simulator.

Doc Block
Apr 15, 2003
Fun Shoe
I meant the code you linked to.

pokeyman
Nov 26, 2006

That elephant ate my entire platoon.

duck monster posted:

Now. What actually is Copy with zone, for curiosity sake.

It's a lot like alloc with zone.

(I'm not really sure what zones are. All I know is they relate to memory and are an unused relic from the nextstep days.)

duck monster
Dec 15, 2004

Doc Block posted:

I meant the code you linked to.

Ah right my bad. It does however seem to work with whatever structures CJSON shits out, so it works for me.

zero knowledge
Apr 27, 2008
IIRC the notion of zones was that you could create yourself a zone for your library and allocate all your memory inside of it, so it was kind of a piece of metadata on an allocation that could link it vaguely back to its purpose or origin. Then, when you knew that your library was done doing whatever, you could just free the entire zone in one go instead of having to track each allocation and freeing it at the appropriate time.

It's an idea that's got a lot of problems, which is why it's not been used in several years in favor of just releasing objects when you're done with them (or better still with autorelease pools and eventually ARC), but apparently it provided some pretty huge performance wins in its day.

Bob Morales
Aug 18, 2006


Just wear the fucking mask, Bob

I don't care how many people I probably infected with COVID-19 while refusing to wear a mask, my comfort is far more important than the health and safety of everyone around me!

Is there any legitimate reason for Apple to charge $99 for EACH developer program (Mac and iOS)? Accounting? Pure evilness?

I know the only thing the $99 really gets me on the Mac side is the Mac App store but c'mon.

stray
Jun 28, 2005

"It's a jet pack, Michael. What could possibly go wrong?"
Can someone help me understand the UITableViewDelegate protocol? Specifically, I'm trying to understand the tableView:didSelectRowAtIndexPath: method a bit better. A lot of books and guides give you ready-made code and I understand that an NSIndexPath is basically a map to drill down through a series of nested arrays to a specific item, but I don't quite understand the code.

For example, I've got a plist which is an array of dictionaries. Each dictionary is comprised of a series of strings representing the various details for a branch (e.g., name, address, phone, etc.) I'm reading this plist and building a UITableView from it with (alphabetized) sections and items. When a user taps a branch, it pushes a new view onto the stack which displays the branch's info.

Here's the relevant line in the tableView:didSelectRowAtIndexPath: method:
code:
// branchDetails is an NSDictionary used to populate the fields in the new view.
branchView.branchDetails = 
[
 [self.sections valueForKey:
  [
   [
    [self.sections allKeys] 
   sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)] 
  objectAtIndex:indexPath.section]
 ] 
objectAtIndex:indexPath.row];
This code works, but I'm not really sure why, because there's way too much going on in this one line for me to understand it. Can anyone explain this to me?

stray fucked around with this message at 21:07 on Feb 27, 2012

Zhentar
Sep 28, 2003

Brilliant Master Genius
An NSIndexPath just tells you "the user selected row 13 in section 2".

code:
 [self.sections valueForKey:
  [
   [
    [self.sections allKeys] 
   sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)] 
  objectAtIndex:indexPath.section]
 ] 
Is just saying "get me the list of what's in section 2" (in a complicated way because NSDictionary isn't ordered, and it's a stupid way of organizing your data for a tableview)

and then
code:
[
objectAtIndex:indexPath.row];
Is just "get me what's in row 13 of that section".

PT6A
Jan 5, 2006

Public school teachers are callous dictators who won't lift a finger to stop children from peeing in my plane

Bob Morales posted:

Is there any legitimate reason for Apple to charge $99 for EACH developer program (Mac and iOS)? Accounting? Pure evilness?

Evil, I'm pretty sure. It also explains why they use a method which incurs $30 of bank fees every time money is transferred into your account when Google doesn't, and why they have stupid minimums for disbursement, and an application process which takes over a month. They literally want you to hurt as a result of doing business with them, as far as I can tell. But you have no choice, because you'll still make more money off paid iOS apps than Android apps for the time being. You/we are their bitch.

stray
Jun 28, 2005

"It's a jet pack, Michael. What could possibly go wrong?"

Zhentar posted:

NSDictionary isn't ordered, and it's a stupid way of organizing your data for a tableview
OK, so what's a better way of organizing my data for a tableview? (I'm not at the "Core Data" level, yet.)

Simulated
Sep 28, 2001
Lowtax giveth, and Lowtax taketh away.
College Slice

PT6A posted:

Evil, I'm pretty sure. It also explains why they use a method which incurs $30 of bank fees every time money is transferred into your account when Google doesn't, and why they have stupid minimums for disbursement, and an application process which takes over a month. They literally want you to hurt as a result of doing business with them, as far as I can tell. But you have no choice, because you'll still make more money off paid iOS apps than Android apps for the time being. You/we are their bitch.

What? I don't get charged any bank fees for my deposits. Perhaps that is just your bank doing it?

stray posted:

OK, so what's a better way of organizing my data for a tableview? (I'm not at the "Core Data" level, yet.)

Well if you don't want to use CoreData and the NSFetchedResultsController then just store the items in an NSArray and use one section and the row as the index into the array. Trying to support sections, sorting, etc without using CoreData is just a good way to get confused and random crashes IMHO, but you would essentially use an NSArray to store the items and another NSArray where the contents of the array is an NSNumber pointing into the original array. If you use sections then you need another layer of indirection for the sections.

There are more efficient data structures of course but at that point just learn CoreData and then you get stuff like searching/indexing and delegate notifications when the results of the fetch change so you can do fancy stuff like have a background thread inserting/deleting objects and have your table view reflect those changes in fancy slide in-out animations (or cross-fade when values change... or have a changed row show a "saving..." detail label and update to the new value when the save actually succeeds on the server). Again, you can do all this without CoreData by using proper data structures, KVO, et al but why?


I am typing up some info about RestKit - should be posted shortly.

Simulated
Sep 28, 2001
Lowtax giveth, and Lowtax taketh away.
College Slice
OK Here is some basic kickstart info for RestKit. A word of caution… RestKit is currently undergoing some refactoring and improvements that add stuff like a built-in table controller, block support, automatic cache support, etc. Whenever that stuff is done and gets merged into master some best-practices will change. (The idea is that the table controller will have a refresh policy and automatically pull objects from the server when they are stale and will auto-delete orphaned objects from CoreData when they are deleted on the server. You just supply a block to configure the cell based on the property values and it does the rest.)

First, hit up the github project page: https://github.com/RestKit/RestKit. It has recently been updated with much simpler instructions for getting RestKit integrated into your Xcode workspace. For those who used to have to link in five different static libraries, fuss with header file output paths, and other bullshit that has all been eliminated. Now there is one .o file for iOS (and one package for MacOS) that includes everything you need. The headers are placed in the workspace derived data folder so Xcode should know how to find them.

Once you have RestKit where it will build and you can import the <RestKit/RestKit.h> file you are ready to proceed.

For each of the major RestKit entry points there is a shared item that becomes the default item, e.g.:
[RKClient sharedClient]. I typically setup a #define XClient [RKClient sharedClient], etc. Then you initialize the shared items in your app delegate and they can be accessed anywhere else. You also typically define the base URL there and let everything else use a relative URL.
code:
#define XAppDelegate ((AppDelegate *)[[UIApplication sharedApplication] delegate])
#define XNotificationCenter [NSNotificationCenter defaultCenter]
#define XObjectManager [RKObjectManager sharedManager]
#define XClient [RKClient sharedClient]
#define XContext [RKObjectManager sharedManager].objectStore.managedObjectContext
#define SAVE_CONTEXT() [[RKObjectManager sharedManager].objectStore save]
code:
[RKClient setSharedClient:[RKClient clientWithBaseURL:XAppDelegate.lastUsedUrl 
	username:self.usernameField.text 
	password:self.passwordField.text]];
XClient.disableCertificateValidation = YES;
XClient.requestQueue.showsNetworkActivityIndicatorWhenBusy = YES;
There are several key pieces of RestKit and they each build on each other:

RKClient layer - this networking layer takes care of building requests and getting responses. The requests are put onto a background queue that can automatically trigger the network activity indicator, will perform up to five requests in-flight at once (and queues additional requests), etc. It can communicate over SSL (and you can tell it to ignore certificate validity to use self-signed certs). It also supports HTTP AUTH schemes like digest and Kerberos so you can supply a username/password and it will log you in.

If you are using RKClient, then your controller needs to implement RKRequestDelegate. I find the best way to learn is often code so here is how you can fire off a get request and check the response:

code:
- (void)getConnectionVersion {
	RKRequest *r = [XClient get:@"Version" delegate:self];
	r.userData = REQ_GET_VERSION;
}
- (void)request:(RKRequest *)request didLoadResponse:(RKResponse *)response
{
    if(request.userData == REQ_GET_VERSION) 
    {
        if(!response.isOK)
        {
            [self showError:response.failureErrorDescription isError:YES];
        }
        else 
        {
            NSString *serverVersion = response.bodyAsString;

            //snipped code
                
            RKRequest *r2 = [XClient get:@"MyPermissions" delegate:self];
            r2.userData = REQ_GET_PERMISSIONS;
        }
    }
	else if (request.userData == REQ_GET_PERMISSIONS)
	{
		//omitted
	}
}
- (void)request:(RKRequest *)request didFailLoadWithError:(NSError *)error
{
    if(request.userData == REQ_GET_VERSION || request.userData == REQ_GET_PERMISSIONS)
    {
        NSLog(@"error getting version: %@", error);
        [self showError:[NSString stringWithFormat:@"Could not connect to system:\n%@", error] isError:YES];
    }
}
OK a couple of things demonstrated here… one, my URLs are relative. This makes it easy to switch the base URL to dev/prod servers or in my case when everyone who uses the app will have a different URL.

Second, the request is fired off immediately when I call get:delegate: on a background queue. However I can add userData to the request object safely because the response will be handled on the main thread, guaranteeing that the delegate response methods can't be invoked until the current run through the event loop is finished.

Third, notice the convenience methods on the response object that allow you to check the HTTP response codes or get the response body as a string.

Lastly, note how I am chaining requests when the situation calls for it. I know that probably seems obvious but some people want to know how you can make one request wait for a response from another so there it is.


Here's another example of doing a PUT, only in this case I want to PUT the data as a raw quoted string (due to WCF incorrectly treating plain string input parameters in JSON mode as "string" instead of {"string"}):

code:
        NSString *reqString = [NSString stringWithFormat:@"\"%@\"", [imgData base64Encoded]];
        RKRequestSerialization *p = [RKRequestSerialization serializationWithData:
				[reqString dataUsingEncoding:NSUTF8StringEncoding] 
				MIMEType:RKMIMETypeJSON];
        RKRequest *request = [XClient put:[NSString stringWithFormat:@"Students/%i/Photo", 
							[student.studentId intValue]] 
                                   params:p 
                                 delegate:self];
        request.userData = [NSDictionary dictionaryWithObjectsAndKeys:student, @"student", img, @"studentPhoto", nil];
The key RestKit bits here are that I am creating RKRequestSerialization which just says "hey rest kit - I'm going to provide you the data for this PUT or POST request so don't do anything fancy". You simply provide the data and the MIME type and RestKit will dutifully report to the server that it is sending data of that type. You can also do multi-part form requests in a somewhat similar way, or if you supply an NSDictionary it will spit out form-encoded key-value pairs.


The next piece of RestKit is the Object Mapping layer which will be described in my next post. Following that is the CoreData integration.

Simulated fucked around with this message at 23:32 on Feb 27, 2012

lord funk
Feb 16, 2004

:words: :woop:

Thanks Ender, saving that post.

Toady
Jan 12, 2009

Bob Morales posted:

Is there any legitimate reason for Apple to charge $99 for EACH developer program (Mac and iOS)? Accounting? Pure evilness?

I know the only thing the $99 really gets me on the Mac side is the Mac App store but c'mon.

Also access to the developer forums, engineer support, pre-release software, free copies of OS X and OS X Server. Would be nice if the price of one program was reduced if you were in the other, though.

Luigi Thirty
Apr 30, 2006

Emergency confection port.

Coming from a C and Java background Xcode should come with a swear jar for every time you use int instead of NSNumber. :smithicide:

The Objective-C syntax is weird as hell to me but I like it better than Android development if only from a "the operating system is not hacked together from a bunch of little pieces glued together into the rough shape of a cube" aspect.

Luigi Thirty fucked around with this message at 09:01 on Feb 28, 2012

Adbot
ADBOT LOVES YOU

dizzywhip
Dec 23, 2005

Why would you want to replace every int with an NSNumber? That would introduce a bunch of overhead for no reason. Typically the only time I ever use them is when I need to store numbers in a container class that only stores objects.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply