Thursday, October 18, 2012

debug iphone app wait for lunch


For Xcode 4 you have to:
  1. Edit your active scheme via "Schemes" dropdown.
  2. Than choose your product - 'Run MyApp.app' on the left.
  3. Select 'Info' tab on the right.
  4. And finally choose "Wait for MyApp.app to launch" option.
More here in "Customize Executables in the Scheme Editor" section.

Wednesday, October 17, 2012

iphone basic


Discover Whether an Object Is an Instance of a Particular Class or its Subclasses

To discover whether an object is an instance of a class or its subclasses, call the isKindOfClass: method on the object. An app sometimes makes this check when it wants to discover the messages (implemented or inherited) that an app responds to.
static int sum = 0;
for (id item in myArray) {
    if ([item isKindOfClass:[NSNumber class]]) {
        int i = (int)[item intValue];
        sum += i;
    }
}
The isKindOfClass: method takes an object of type Class as a parameter; to get this object, you call the class method on the class symbol. Then evaluate the Boolean value returned by this method and proceed accordingly.
NSObject declares other methods for discovering information about object inheritance. The isMemberOfClass: method, for example, tells you whether an object is an instance of a specific class, whereas isKindOfClass: tells you whether the object is a member of that class or any of its descendent classes.

Discover Whether an Object Responds to a Message

To discover whether an object responds to a message, call the respondsToSelector: method on the object. App code often verifies that an object responds to a message before it sends the message to the object.
if ([item respondsToSelector:@selector(setState:)]) {
    [item setState:[self.arcView.font isBold] ? NSOnState : NSOffState];
}
The respondsToSelector: method takes a selector as its parameter. A selector is an Objective-C data type for runtime identifiers of methods; you specify a selector using the @selector compiler directive. In your code, evaluate the Boolean value returned by this method and proceed accordingly.
For identifying the messages an object responds to, calling respondsToSelector: is generally more useful than evaluating class type. For example, a more recent version of a class might implement a method that isn’t found in a prior version.

Discover Whether an Object Conforms to a Protocol

To discover whether an object conforms to a protocol, call the conformsToProtocol: method on the object.
- (void) setDelegate:(id __weak) obj {
    NSParameterAssert([obj conformsToProtocol:
        @protocol(SubviewTableViewControllerDataSourceProtocol)]);
    delegate = obj;
}
The conformsToProtocol: method takes a runtime identifier of a protocol as a parameter; you specify this identifier using the @protocol compiler directive. Evaluate the Boolean value returned by this method and proceed accordingly. Note than an object can conform to a protocol without implementing its optional methods.

Compare Objects

You can compare two objects by using the isEqual: method. The object receiving the message is compared to the passed-in object; if they’re the same, the method returns YES. For example:
BOOL objectsAreEqual = [obj1 isEqual:obj2];
if (objectsAreEqual) {
    // do something...
}
Note that object equality is different from object identity. For the latter, use the equality operator == to test whether two variables point to the same instance.
What is compared when you compare two objects of the same class? That depends on the class. The root class, NSObject, uses pointer equality as the basis of comparison. Subclasses at any level can override their superclass’s implementation to base the comparison on class-specific criteria, such as object state. For example, a hypothetical Person object might equal another Person object if the first-name, last-name, and birth-date attributes of both objects match.
The value and collection classes of the Foundation framework declare comparison methods of the form isEqualToType:, where Type is the class type minus the NS prefix—for example, isEqualToString: and isEqualToDictionary:. The comparison methods assume that the passed-in object is of the given type and raise an exception if it is not.

Copy Objects

You make a copy of an object by sending a copy message to it.
NSArray *myArray = [yourArray copy];
To be copied, the class of the receiving object must conform to the NSCopying protocol. If you want your objects to be copyable, you must adopt and implement the copy method of this protocol.
You sometimes copy an object obtained from elsewhere in a program when you want to ensure the object’s state does not change while you’re using it.
Copying behavior is specific to a class and depends upon the specific nature of the instance. Most classes implement deep copying, which makes a duplicate of all instance variables and properties; some classes (for example, the collection classes) implement shallow copying, which only duplicates the references to those instance variables and properties.
Classes that have mutable and immutable variants also declare a mutableCopy method to create a mutable copy of an object. For example, if you call mutableCopy on an NSString object, you get an instance of NSMutableString.

Friday, October 12, 2012

NSURL parsing

got something good, paste it here


- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
NSLog(@"%@", url);
    NSURL *url1 = [NSURL URLWithString:@"httpdd://www.mobileorchard.com"];
    NSLog(@"scheme: %@", [url scheme]);
    NSLog(@"host: %@", [url host]);
    NSLog(@"port: %@", [url port]);
    NSLog(@"path: %@", [url path]);
    NSLog(@"path components: %@", [url pathComponents]);
    NSLog(@"parameterString: %@", [url parameterString]);
    NSLog(@"query: %@", [url query]);
    return YES;
}

@interface NSString (ParseCategory)
- (NSMutableDictionary *)explodeToDictionaryInnerGlue:(NSString *)innerGlue outterGlue:(NSString *)outterGlue;
@end
@implementation NSString (ParseCategory)
- (NSMutableDictionary *)explodeToDictionaryInnerGlue:(NSString *)innerGlue outterGlue:(NSString *)outterGlue {
    // Explode based on outter glue
    NSArray *firstExplode = [self componentsSeparatedByString:outterGlue];
    NSArray *secondExplode;

    // Explode based on inner glue
    NSInteger count = [firstExplode count];
    NSMutableDictionary *returnDictionary = [NSMutableDictionary dictionaryWithCapacity:count];
    for (NSInteger i = 0; i < count; i++) {
        secondExplode = [(NSString *)[firstExplode objectAtIndex:i] componentsSeparatedByString:innerGlue];
        if ([secondExplode count] == 2) {
                [returnDictionary setObject:[secondExplode objectAtIndex:1] forKey:[secondExplode objectAtIndex:0]];
        }
    }

    return returnDictionary;
}
@end
It's called like this:
NSMutableDictionary *parsedQuery = [[myNSURL query] explodeToDictionaryInnerGlue:@"=" outterGlue=@"&"]
For parsing the path portion of the NSURL (ie @"/partA/partB/partC"), just call this:
NSArray *parsedPath = [[nyNSURL path] componentsSeperatedByString:@"/"];
Be aware that parsedPath[0] will be an empty string because of the leading /!
EDIT - Here is a Category extension to NSURL for your usage pleasure. It strips the initial "/" so you don't have an empty 0 index.
@implementation NSURL (ParseCategory)
- (NSArray *)pathArray {
    // Create a character set for the slash character
    NSRange slashRange;
    slashRange.location = (unsigned int)'/';
    slashRange.length = 1;
    NSCharacterSet *slashSet = [NSCharacterSet characterSetWithRange:slashRange];

    // Get path with leading (and trailing) slashes removed
    NSString *path = [[self path] stringByTrimmingCharactersInSet:slashSet];

    return [path componentsSeparatedByCharactersInSet:slashSet];
}
- (NSDictionary *)queryDictionary {
    NSDictionary *returnDictionary = [[[[self query] explodeToDictionaryInnerGlue:@"=" outterGlue:@"&"] copy] autorelease];
    return returnDictionary;
}
@end
share|improve this answer

difference between a strong and weak pointer


Objective-C (programming language): In Objective-C, what's the difference between a strong and weak pointer?

 (1)
 

2 Answers

Strong and weak are keywords that help you manage the Automatic Reference Counting (ARC) of the XCode environment and are a part of the new way of managing memory in Objective-C. To understand the difference, you must first understand how memory is implicitly managed by objects in XCode. 

Each object has a property that tracks the number of other objects that require/reference it. This property is called the reference count. In the old way of doing things, you would specifically tell the object to be retained (increase its reference count). When you did this, you would also have to explicitly tell the object to decrease its reference count (release) when you were done with it.

When an object’s reference count reaches zero, it is destroyed and its memory return to the heap where it can be reused. If you forgot to retain the object, it could potentially be destroyed earlier than you intended and cause an error in your program—there are reasons why you wouldn’t retain an object, but I’ll get into that further down. If you forgot to release the object, or your program was structured in such a way it could never be released, it could reside in memory long after you were done with it, causing a memory leak which could slow your app down or potentially crash it.

Now, with ARC you no longer have to explicitly tell an object to be retained or released. Pointers are automatically created with strong references; they are automatically retained. In this case, the strong keyword is implied when creating pointers, though you can use it if you want.

However there are times when you don’t want to retain an object (i.e. increase its reference count). To do this, you use the weak keyword when creating the pointer. Your pointer will still point to the object, but if that object is destroyed then using the pointer will cause a program error.

Why would you use a weak reference?

Well, one reason is if you have objects in parent-child relationships where the parent keeps pointers to its children and every child keeps a pointer to its parent. The potential with this structure is that you could no longer need your parent object and XCode will implicitly release it, but because its children keep a reference to it, the parent and its children can remain in memory even though you no longer have a way of accessing them. This is called a retain cycle.

To avoid the retain cycle, the children objects should only maintain a weak pointer to their parents. The reason for this is that when the parent is told to destroy itself, the children would be destroyed first so there is no chance they could access their parent after it had been destroyed.

atomic and noatomic


The last two are identical; "atomic" is the default behavior (note that it is not actually a keyword; it is specified only by the absence of nonatomic).
Assuming that you are @synthesizing the method implementations, atomic vs. non-atomic changes the generated code. If you are writing your own setter/getters, atomic/nonatomic/retain/assign/copy are merely advisory. (Note: @synthesize is now the default behavior in recent versions of LLVM. There is also no need to declare instance variables; they will be synthesized automatically, too, and will have an_ prepended to their name to prevent accidental direct access).
With "atomic", the synthesized setter/getter will ensure that a whole value is always returned from the getter or set by the setter, regardless of setter activity on any other thread. That is, if thread A is in the middle of the getter while thread B calls the setter, an actual viable value -- an autoreleased object, most likely -- will be returned to the caller in A.
In nonatomic, no such guarantees are made. Thus, nonatomic is considerably faster than "atomic".
What "atomic" does not do is make any guarantees about thread safety. If thread A is calling the getter simultaneously with thread B and C calling the setter with different values, thread A may get any one of the three values returned -- the one prior to any setters being called or either of the values passed into the setters in B and C. Likewise, the object may end up with the value from B or C, no way to tell.
Ensuring data integrity -- one of the primary challenges of multi-threaded programming -- is achieved by other means.

The last two are identical; "atomic" is the default behavior (note that it is not actually a keyword; it is specified only by the absence of nonatomic).
Assuming that you are @synthesizing the method implementations, atomic vs. non-atomic changes the generated code. If you are writing your own setter/getters, atomic/nonatomic/retain/assign/copy are merely advisory. (Note: @synthesize is now the default behavior in recent versions of LLVM. There is also no need to declare instance variables; they will be synthesized automatically, too, and will have an_ prepended to their name to prevent accidental direct access).
With "atomic", the synthesized setter/getter will ensure that a whole value is always returned from the getter or set by the setter, regardless of setter activity on any other thread. That is, if thread A is in the middle of the getter while thread B calls the setter, an actual viable value -- an autoreleased object, most likely -- will be returned to the caller in A.
In nonatomic, no such guarantees are made. Thus, nonatomic is considerably faster than "atomic".
What "atomic" does not do is make any guarantees about thread safety. If thread A is calling the getter simultaneously with thread B and C calling the setter with different values, thread A may get any one of the three values returned -- the one prior to any setters being called or either of the values passed into the setters in B and C. Likewise, the object may end up with the value from B or C, no way to tell.
Ensuring data integrity -- one of the primary challenges of multi-threaded programming -- is achieved by other means.