Tuesday, December 10, 2013

beginBackgroundTaskWithExpirationHandler

We can use beginBackgroundTaskWithExpirationHandler to ensure that a task doesn't get stopped abruptly This is how I used 

- (void)didReceiveObjList:(CFDataRef)message
{
    // Received List Of Objects. Processing the list can take a few seconds.
    // So doing it in separate thread with expiration handler to ensure it gets some time    to do the task even if the app goes to background.

        UIApplication *application = [UIApplication sharedApplication];
__block UIBackgroundTaskIdentifier bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
[application endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}];
    
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
         [self processObjList:message];
[application endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
});

NSLog(@"Main Thread proceeding...");

}

Monday, December 9, 2013

UITableViewWrapperView in iOS7

In iOS7, a view is included in between UITableView and UITableViewCell, named UITableViewWrapperView. [This was not there till iOS 6].

UITableViewWrapperView is a superview of the UITableViewCell, and UITableView is the superview of UITableViewWrapperView

UITableView - > UITableViewWrapperView -> UITableViewCell

Wednesday, November 27, 2013

Getting the screen size in iOS

To get the screen size in iOS available for the app,

        CGFloat fScreenHeight = 0.0;

        if (UIDeviceOrientationIsLandscape([[UIDevice currentDevice] orientation])) {
            fScreenHeight = [UIScreen mainScreen].applicationFrame.size.width;
        }
        else{
            fScreenHeight = [UIScreen mainScreen].applicationFrame.size.height;
        }

        NSLog(@"Screen Height = %02f", fScreenHeight);

We can get the screen width by doing just vice versa. 

This will give us the screen size available for the app, i.e. after reducing the height of the status bar. For iPhone in portrait mode this will give the height as 460, which is 480-20.

Tuesday, October 8, 2013

To capture TCP Packets in Mac OS X


In Terminal  use the below command:

sudo tcpdump -s0 -n -il0 -w l0.cap

This will dump the packet info in the user’s home directory. This can be viewed using Wireshark. 

Monday, October 7, 2013

Viewing Cookie Values in Mozilla

There's an easy way to see cookie values in Mozilla Firefox [I'm trying this in Mozilla Firefox 25.0 now] :

1. Go to Tools-> Options -> Privacy
2. Under the 'History' section, there are two options to delete the cookies: 
      i.  Clear your recent history or 
      ii. Remove individual cookies



Choose the second option, which lists all the cookies. You can select the host and under each host, the cookies are listed. Once you select a cookie, its value(content) will be displayed at the bottom



That's where quickr.com stores my preferred city as bangalore. Caught Him red-handed!!! :)

Thursday, October 3, 2013

Getting the next multiple of 4

To get the integer which is the next multiple of 4:

(x+3) &~0x03

If x is a multiple of 4, it will give x itself, otherwise the closest integer greater than x which is a multiple of 4.

Friday, September 20, 2013

Starting an application/process from code in OS X

NSString *strArg = @"arg";  //specifying the variable arg
    
NSWorkspace *workspace = [NSWorkspace sharedWorkspace];
NSURL *url = [NSURL fileURLWithPath:[workspace fullPathForApplication:@"Full-Path-To-The-App-To-Start"]];  //e.g. /Applications/TextEdit.app

NSError *error = nil;
NSArray *arguments = [NSArray arrayWithObjects:@"-d", @"-b", strArg, nil];
[workspace launchApplicationAtURL:url options:0 configuration:[NSDictionary dictionaryWithObject:arguments forKey:NSWorkspaceLaunchConfigurationArguments] error :&error];

//Handle error


Wednesday, September 18, 2013

Combining 2 values into a single Byte

Doing & 0x0F and & 0xF0:

& is the bitwise AND operator. "& 0x0F" is sometimes done to replace the first 4 bits with 0s, or ignore the first(leftmost) 4 bits in a value.

0x0f = 00001111. So a bitwise & operation of 0x0f with any other bit pattern will retain only the rightmost 4 bits, clearing the left 4 bits.

If the input has a value of 01010001, after doing &0x0F, we'll get 00000001 - which is a pattern we get after clearing the left 4 bits.

Just as another example, this is a code I've used in a project:

Byte verflag = (Byte)(bIsAck & 0x0f) | ((version << 4) & 0xf0). Here I'm combining two values into a single Byte value to save space because it's being used in a packet header structure. bIsAck is a BOOL and version is a Byte whose value is very small. So both these values can be contained in a single Byte variable. 

The first nibble in the resultant variable will contain the value of version and the second nibble will contain the value of bIsAck. I can retrieve the values into separate variables at the receiving by doing a 4 bits >> while taking the value of version.

Friday, September 13, 2013

Undefined symbols for architecture ... Build Error

Sometimes we get the below error while building a project in XCode. It's not very troublesome, but sometimes we forget how to fix it:

Undefined symbols for architecture x86_64:

  "_OBJC_CLASS_$_", referenced from:
      _OBJC_CLASS_$_VariableOne in ClassOne.o
      _OBJC_CLASS_$_VariableTwo in ClassTwo.o
          ...
  "_OBJC_METACLASS_$_IpcObject", referenced from:
      _OBJC_METACLASS_$_VariableOne in ClassOne.o
      _OBJC_METACLASS_$_VAriableTwo in ClassTwo.o
      ...

This error shows usually because the compiler build doesn't recognise the mentioned object file( in the above error log. 

Fixing this could be as simple as adding the .m file in the "Compile Sources" list in the Project Settings > Build Phases page

Monday, September 9, 2013

Strange NSThread issue in Objective C

I was trying to start a new thread, with the below code, in an OS X command line tool:

.h
NSThread *srvThread;

.mm
srvThread = [[NSThread alloc] initWithTarget:self selector:@selector(serverThreadFunc:)     object:@"Dummy"];

[srvThread start];
        
Everything was just proper in the selector also, but the new thread never started. I tried different possibilities, verified things over and again ... but the thread didn't start. 

Finally, tired, I was trying to just see the running status of the thread, with the below code:


        if ([srvThread isCancelled]) {
            NSLog(@"New Thread is in Cancelled State");
        } else if ([srvThread isExecuting]) {
            NSLog(@"New Thread is in Executing State");
        } else if ([srvThread isFinished]) {
            NSLog(@"New Thread is in Finished State");

        }

And what a surprise, the thread started working at once. The result I got was :

2013-09-10 10:19:31.896 AvConnectCli[1389:303] New Thread is in Executing State
2013-09-10 10:19:31.896 AvConnectCli[1389:2003] Started Server thread

I'm still checking what was the reason behind it for not starting the thread all these times. Maybe there should've a need for something for the Main thread to continue(there was nothing more in the main thread. It was end of the function). Will update if I can find proper reason for it. 

Again, I commented the thread state checking code and added this:

srvThread = [[NSThread alloc] initWithTarget:self selector:@selector(serverThreadFunc:) object:@"Dummy"];
[srvThread start];
        
for(int i=0;i<1000;i++){
     NSLog(@"%d",i);
}

//        if ([srvThread isCancelled]) {
//            NSLog(@"New Thread is in Cancelled State");
//        } else if ([srvThread isExecuting]) {
//            NSLog(@"New Thread is in Executing State");
//        } else if ([srvThread isFinished]) {
//            NSLog(@"New Thread is in Finished State");

//        }


Now also it's working just fine. The reason was because the main thread was ending soon after it spawned the new thread. The program was ending there. This could not be an issue which will be faced by many, but for starters, who try to just try out multithreading in Objective C, this can cause some confusion. 

Monday, August 26, 2013

"Unknown Type Name ..." error in Objective C/ XCode

XCode sometimes shows this error when we include header files in a cyclic manner:

e.g

B.h
#import "A.h"

A.h

#import "B.h"

I got this error when I had an instance of class A as a member of class B and an instance of class B as a member of class A.

Resolution:

Used "@class A" forward declaration in B.h and imported A.h in B.mm

Friday, July 26, 2013

iOS - To print if the code is running on main thread or not.

NSLog(@"Code is%@ running on Main Thread", ([NSThread isMainThread] ? @"" : @" NOT"));