Appcelerator Titanium for Android: Handling Multiple Screens & Resolutions

titanium-logo_0

Resolution is the quantity of pixels on the physical area of the screen. When Android supports multiple screens, the applications don’t interact with the resolution directly. What matters for the application is the screen size and density conforming to the generalized size and density groups using cross platform mobile development.

Density-independent pixel

The density-independent pixel (dp) is equivalent to one physical pixel on a 160 dpi screen, which is the baseline density assumed by the system for a “medium” density screen. At runtime, the system transparently handles any scaling of the dp units, based on the actual density of the screen in use. The conversion of dp units to screen pixels is simple: px = dp * (dpi / 160). For example, on a 240 dpi screen, 1 dp is equivalent to 1.5 physical pixels.

All iOS devices (iPad, iPhone, iPod) feature the same screen resolution. If that is not the case, they still have the same display points even across generations.  In particular, older non-retina iDevices features a display resolution of 320 X 480 whereas the new retina devices come with twice the amount of resolution at 640 X 960. But they have the same display grid of 320 x 480. Even Apple’s iPad have the display grid of 1024 X 768, whether its retina or not. This benefits the developers as they can create an app for the first-generation iDevice, which will work well on all iDevices without altering the design much. This is made possible due to ‘Display Independent Pixel’, the default unit of display.

On the other hand, Android can be installed in a variety of devices with different resolution and screen sizes. Here we have the default unit of display as the actual pixel. Both the resolution and the display grid are not consistent across multiple devices and vendors. Even if the pixel is the default unit for display you can make use of the following measures:

  • Measurement (mm/cm/in)

Specify the size of the control or resource in terms of actual millimeters, centimeters or inches as required.

  • Percentage (%)

This is the relative unit of measurement with respect to the parent container. Suppose the container is required to occupy the full width of the screen, then define its width property as ‘100%’ . Otherwise, if two horizontal controls are required, each having half the width of screen, then mark the width property as 50% for each control. This is figuratively shown in the image below when two buttons are labeled with ‘No’ and ‘Yes’.

  • Calculation

Another method is adopted when the size of the control doesn’t matter, but we want a certain number of controls to be displayed on the screen. Here we calculate the size of the control by dividing the height/width of the screen with number of controls required. For example, if there is a screen with certain resolution and you need five controls to be displayed vertically. Then I would capture the height of the device with ‘Titanium.Platform.displayCaps.platformHeight’, which would return the height of the device (in points, not necessarily in pixels). Afterwards, divide the result with 5 for five controls.

  • Print Typography (pt)

This unit is the same as what we follow in printed article and they represent the printed points on the paper

By way of a code example, you can see how these units work. However, there is no restriction on mixing these units.

The above code will create a window and add a label above a green box with a height and width of 200 pixels. HVGA screen is here used for demonstration. You can find that the box looks very small when compared to the device’s width and height.

 

The above issue can be resolved by altering the code as given below.

 

The box becomes larger even when it is used with the same measurement, as shown below.

 

Along with the position and size of the controls and views the size of the images to be displayed on the screen should be taken into account. The native developers can use ‘Draw 9-patch’ on their images. In the Titanium framework, different images are used for various screen densities.Titanium developer just need to fix the right size in the right folder and the Appcelerator Titanium framework ensures the right image is displayed on the device. There is no need to write separate image path.

If you want to keep the image in a subfolder, you can use it in “Resources/android/images/<density folder>/subfolder/test.png” and refer it in the app as “image/subfolder/test.png”. These folders are searched for images from the most specific to the general. You can create a folder titled “res-mdpi”, if an image doesn’t exist in one of the other folders it will look there for it last before it fails to find the image. It is the default folder. For simplicity using “high”, “medium”, and “low” is the same as using “res-hdpi”, “res-mdpi”, and “res-ldpi”.

Below is the diagram showing the specific folders we can have to store our image. Once again there is no need to mention the long directory names in our app.

Relationship between C and Objective C

Relationship between C and Objective C

Objective-C is a strict superset of C, which means that it’s possible to seamlessly combine both languages in the same source file. In fact, Objective-C relies on C for most of its core language constructs, so it’s important to have at least a basic foundation in C before tackling the higher-level aspects of the language.
This module provides a concise overview the C programming language. We’ll talk about comments, variables, mathematical operators, control flow, simple data structures, and the integral role of pointers in Objective-C programs. This will give us the necessary background to discuss Objective-C’s object-oriented features.

Structs in Objective C?

// main.m
#import <Foundation/Foundation.h>

typedef struct {
     int rollNumber;
     char name ;
     float fees;
} Student;

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        Student  anyOne = {100,"XYZ",22470};
        NSLog(@"Your student details  is (rollNumber: %d, name: %c, fees: %f)",
              anyOne.rollNumber,anyOne.name, anyOne.fees);
    }
    return 0;
}

Typedef in Objective C?

The typedef keyword lets you create new data types or redefine existing ones. After typedef’ing an unsigned char in the following example, we can use ColorComponent just like we would use char, int, double, or any other built-in type:

// main.m
#import <Foundation/Foundation.h>

typedef unsigned char ColorComponent;

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        ColorComponent red = 255;
        ColorComponent green = 160;
        ColorComponent blue = 0;
        NSLog(@"Your paint job is (R: %hhu, G: %hhu, B: %hhu)",
              red, green, blue);
    }
    return 0;
}

Fast Enumeration in Objective C ?

Fast Enumeration is also known as for-in loop. It’s a more efficient way to iterate over Objective-C collections like NSSet and NSArray than the traditional for and while loops.

// For-in loops ("Fast-enumeration," specific to Objective-C)
NSArray *models = @[@"Ford", @"Honda", @"Nissan", @"Porsche"];
for (id model in models) {
    NSLog(@"%@", model);
}

How to Install COCOS2D in Xcode

How to Install COCOS2D in Xcode

1. You Download COCOS2D latest version from
http://www.cocos2d-iphone.org/download&#8221; this .link

2. keep it on your desktop

3. open the terminal and type “cd”

4. drag your latest version of -> COCOS2D package folder in to your terminal window.

5. type sudo and open the COCOS2D package folder and drag the “install-templates.sh” file into your terminal windows and press enter.

6. put your system password to install templates.

now open your xcode. you will get the COCOS2D in xcode
now enjoy

What are the Dangers of Method Swizzling in Objective C?

Using method sizzling is like using sharp knives in the kitchen. Some people are scared of sharp knives because they think they’ll cut themselves badly, but the truth is that sharp knives are safer.

Method swizzling can be used to write better, more efficient, more maintainable code. It can also be abused and lead to horrible bugs.

Background

As with all design patters, if we are fully aware of the consequences of the pattern, we are able to make more informed decisions about whether or not to use it. Singletons are a good example of something that’s pretty controversial, and for good reason — they’re really hard to implement properly. Many people still choose to use singletons, though. The same can be said about swizzling. You should form your own opinion once you fully understand both the good and the bad.

Discussion

Here are some of the pitfalls of method swizzling:

  • Method swizzling is not atomic
  • Changes behavior of un-owned code
  • Possible naming conflicts
  • Swizzling changes the method’s arguments
  • The order of swizzles matters
  • Difficult to understand (looks recursive)
  • Difficult to debug

These points are all valid, and in addressing them we can improve both our understanding of method swizzling as well as the methodology used to achieve the result. I’ll take each one at a time.

Method swizzling is not atomic

I have yet to see an implementation of method swizzling that is safe to use concurrently1. This is actually not a problem in 95% of cases that you’d want to use method swizzling. Usually, you simply want to replace the implementation of a method, and you want that implementation to be used for the entire lifetime of your program. This means that you should do your method swizzling in +(void)load. The load class method is executed serially at the start of your application. You won’t have any issues with concurrency if you do your swizzling here. If you were to swizzle in +(void)initialize, however, you could end up with a race condition in your swizzling implementation and the runtime could end up in a weird state.

Changes behavior of un-owned code

This is an issue with swizzling, but it’s kind of the whole point. The goal is to be able to change that code. The reason that people point this out as being a big deal is because you’re not just changing things for the one instance of NSButton that you want to change things for, but instead for all NSButton instances in your application. For this reason, you should be cautious when you swizzle, but you don’t nee to avoid it altogether.

Think of it this way… if you override a method in a class and you don’t call the super class method, you may cause problems to arise. In most cases, the super class is expecting that method to be called (unless documented otherwise). If you apply this same thought to swizzling, you’ve covered most issues. Always call the original implementation. If you don’t, you’re probably changing too much to be safe.

Possible naming conflicts

Naming conflicts are an issue all throughout Cocoa. We frequently prefix class names and method names in categories. Unfortunately, naming conflicts are a plague in our language. In the case of swizzling, though, they don’t have to be. We just need to change the way that we think about method swizzling slightly. Most swizzling is done like this:

@interface NSView : NSObject
- (void)setFrame:(NSRect)frame;
@end

@implementation NSView (MyViewAdditions)

- (void)my_setFrame:(NSRect)frame {
    // do custom work
    [self my_setFrame:frame];
}

+ (void)load {
    [self swizzle:@selector(setFrame:) with:@selector(my_setFrame:)];
}

@end

This works just fine, but what would happen if my_setFrame: was defined somewhere else? This problem isn’t unique to swizzling, but we can work around it anyway. The workaround has an added benefit of addressing other pitfalls as well. Here’s what we do instead:

@implementation NSView (MyViewAdditions)

static void MySetFrame(id self, SEL _cmd, NSRect frame);
static void (*SetFrameIMP)(id self, SEL _cmd, NSRect frame);

static void MySetFrame(id self, SEL _cmd, NSRect frame) {
    // do custom work
    SetFrameIMP(self, _cmd, frame);
}

+ (void)load {
    [self swizzle:@selector(setFrame:) with:(IMP)MySetFrame store:(IMP *)&SetFrameIMP];
}

@end

While this looks a little less like Objective-C (since it’s using function pointers), it avoids any naming conflicts. In principle, it’s doing the exact same thing as standard swizzling. This may be a bit of a change for people who have been using swizzling as it has been defined for a while, but in the end, I think that it’s better. The swizzling method is defined thusly:

typedef IMP *IMPPointer;

BOOL class_swizzleMethodAndStore(Class class, SEL original, IMP replacement, IMPPointer store) {
    IMP imp = NULL;
    Method method = class_getInstanceMethod(class, original);
    if (method) {
        const char *type = method_getTypeEncoding(method);
        imp = class_replaceMethod(class, original, replacement, type);
        if (!imp) {
            imp = method_getImplementation(method);
        }
    }
    if (imp && store) { *store = imp; }
    return (imp != NULL);
}

@implementation NSObject (FRRuntimeAdditions)
+ (BOOL)swizzle:(SEL)original with:(IMP)replacement store:(IMPPointer)store {
    return class_swizzleMethodAndStore(self, original, replacement, store);
}
@end

Swizzling changes the method’s arguments

This is the big one in my mind. This is the reason that standard method swizzling should not be done. You are changing the arguments passed to the original method’s implementation. This is where it happens:

[self my_setFrame:frame];

What line does is:

objc_msgSend(self, @selector(my_setFrame:), frame);

Which will use the runtime to look up the implementation of my_setFrame:. Once the implementation is found, it invokes the implementation with the same arguments that were given. The implementation it finds is the original implementation of setFrame:, so it goes ahead and calls that, but the _cmd argument isn’t setFrame: like it should be. It’s now my_setFrame:. The original implementation is being called with an argument it never expected it would receive. This is no good.

There’s a simple solution — use the alternative swizzling technique defined above. The arguments will remain unchanged!

The order of swizzles matters

The order in which methods get swizzled matters. Assuming setFrame: is only defined on NSView, imagine this order of things:

[NSButton swizzle:@selector(setFrame:) with:@selector(my_buttonSetFrame:)];
[NSControl swizzle:@selector(setFrame:) with:@selector(my_controlSetFrame:)];
[NSView swizzle:@selector(setFrame:) with:@selector(my_viewSetFrame:)];

What happens when the method on NSButton is swizzled? Well most swizzling will ensure that it’s not replacing the implementation of setFrame: for all views, so it will pull up the instance method. This will use the existing implementation to re-define setFrame: in the NSButton class so that exchanging implementations doesn’t affect all views. The existing implementation is the one defined on NSView. The same thing will happen when swizzling on NSControl (again using the NSView implementation).

When you call setFrame: on a button, it will therefore call your swizzled method, and then jump straight to the setFrame: method originally defined on NSView. The NSControl and NSView swizzled implementations will not be called.

But what if the order were:

[NSView swizzle:@selector(setFrame:) with:@selector(my_viewSetFrame:)];
[NSControl swizzle:@selector(setFrame:) with:@selector(my_controlSetFrame:)];
[NSButton swizzle:@selector(setFrame:) with:@selector(my_buttonSetFrame:)];

Since the view swizzling takes place first, the control swizzling will be able to pull up the right method. Likewise, since the control swizzling was before the button swizzling, the button will pull up the control’s swizzled implementation of setFrame:. This is a bit confusing, but this is the correct order. How can we ensure this order of things?

Again, just use load to swizzle things. If you swizzle in load and you only make changes to the class being loaded, you’ll be safe. The load method guarantees that the super class load method will be called before any subclasses. We’ll get the exact right order!

Difficult to understand (looks recursive)

Looking at a traditionally defined swizzled method, I think it’s really hard to tell what’s going on. But looking at the alternative way we’ve done swizzling above, it’s pretty easy to understand. This one’s already been solved!

Difficult to debug

One of the confusions during debugging is seeing a strange backtrace where the swizzled names are mixed up and everything gets jumbled in your head. Again, the alternative implementation addresses this. You’ll see clearly named functions in backtraces. Still, swizzling can be difficult to debug because it’s hard to remember what impact the swizzling is having. Document your code well (even if you think you’re the only one who will ever see it). Follow good practices, and you’ll be alright. It’s not harder to debug than multi-threaded code.

Conclusion

Method swizzling is safe if used properly. A simple safety measure you can take is to only swizzle in load. Like many things in programming, it can be dangerous, but understanding the consequences will allow you use it properly.

How to achieve multiple inheritance in Xcode?

Objective-C doesn’t support multiple inheritance, and you don’t need it. Use composition:

@interface ClassA : NSObject {
}

-(void)methodA;

@end

@interface ClassB : NSObject {
}

-(void)methodB;

@end

@interface MyClass : NSObject {
  ClassA *a;
  ClassB *b;
}

-(id)initWithA:(ClassA *)anA b:(ClassB *)aB;

-(void)methodA;
-(void)methodB;

@end

How to do Git Commit from Terminal in Mac?

1 : initial setup of git repository

 

 rm -rf .git      —> remove all existing .git files

 

 git init          —-> initializing git repository

 git add ./     ——> add all files to git

 git commit ./ -m”final update ater project completion”       —-> commit file to git 

 git remote add origin yourRemoteUrl/other git url   —> ading url to post

 git push -u origin master       —> pushing first time file to master   

2 : after modifications in file 

 git commit ./ -m”test update”

 git push