Inegrating Static Libray written in Objective C to Swift iOS Project

I was looking for integrating my one of the Static library written in Objective-C into new swift project  & you know what I got very little information on it. I struggled alot to make my things working with Objc+swift integration for my project.

Here I will guide you through such integration

1. Suppose you have some static Library XYZ written in Objective-C

Add that library as subproject into your target project as descried HERE

Then we have to create Bridge-header which will make swift code to access Objective C part of your library.

You can just follow
Xocde -> New -> File
there you need to add header file (from iOS/OS X section)
be carefull whilte naming this file. this file should have name like


<product_module_name>-Bridging-Header.h : Default Product module name is project name itself.

you can read more about "Product module name" at Apple Docs


Now add import statements in <product_module_name>-Bridging-Header.h for accessing Native SDK Classes


e.g.

If you have Project with name "sampleSwift" then your bridge file should look like


Background Pattern image to SKScene

Today we are going to see how we can add background pattern image to SKScene

Once, there was  requirement for one of project to set pattern image for SKScene background I tried with backgroundColor property of SKScene like


But it won't work.

So I wrote category to overcome this. Using this category of SKScene you can easily set background  pattern to SKScene without any pain.


Hosting file on Google drive

Google drive provides lots of storage space for storing your personal stuff at free of cost ...& Google provides not just few MBs it allows free storage up to 15GB (can you believe it ?)
You can meet google driver here - GoogleDrive
I am going to share pretty trick for hosting your HTML pages on google drive.

Below steps will guide you throgh

1 . Login to google drive with your google account, You will land up on screen similar to below screen
Then for hosting your content you can create folder (In my case its 'webDocs') as shown below


2 . Go inside newly created folder & upload your file in it (It can contain javascript as well  ) Now move back to your folder.


3 . Right click on the folder and select Share option 


4 . You will given following option for sharing, you go with more option.




5 . Then select "On - Public on the web" option and click save button. (you are almost done).


6 . Now you will have link from google drive for sharing. You just copy it as of now and store somewhere.


7  . Convert saved URL in to URL as given below 
www.googledrive.com/host/[doc id]
E.g. Id https://drive.google.com/folderview?id=<File_ID>&usp=sharing
will be converted to
https://www.googledrive.com/host/<File_ID>/
To get direct link to file just add file name at end of created URL as.
https://www.googledrive.com/host/<File_ID>/<Fille_Name> just hit it.

& you are done !



I have hosted file -bouncing-ball.html in webDocs folder in side google drive. You can have look at it and it contains some javascript also to show how you can play with this feature and create your own one page javascript application & host then on most reliable google servers using google drive.

keepRocking

Difference in strong and weak pointers in ObjectiveC

Before writting this, I assume you know basic knowledge of ObjectiveC and its well known topic of discussion Memory Management If you do not know you can follow tutorials on ObectiveC &  ObjectiveC Memory Management, Here I am going to explain how strong and weak pointers are different in ObjectiveC with some code example.

Consider Sample classes TechClass & MyClass explain, one class have 2 ivars which which points to object of MyClass with strong and weak reference viz. strogPntr & weakPntr as shown below


1
2
3
4
5
6
7
8
@interface MyClass()
@end

@interface TechClass(){
    
    MyClass * strogPntr;
    __weak MyClass * weakPntr;;
}

Now we create MyClass object and assign it to strogPntr. same object is pointed by weakPntr. Now if we assign nil to weakPntr it will not deallocate that object because still there is strong pointer referring to that pointer.


1
2
3
 strogPntr = [MyClass new];
 weakPntr = strogPntr;
 weakPntr = nil;

Pictorial representation of above code is given below
weak-pointer-nil

Lets see whats happens when we try other way around i.e, assigning nil strogPntr. what do you expect here? will object get deallocated or keeps on hanging with weakPntr  pointer ???
Correct answer is object will be deallocated because object do not have any strong pointer pointer to created object of MyClass also due to this now weakPntr will automatically point to nil.


1
2
3
 strogPntr = [MyClass new];
 weakPntr = strogPntr;
 strogPntr = nil;
Pictorial representation of above code is given below


Now onwards keep in mind  that if you want to persistent object inside any viewcontoller/custom object never ever nil all out strong pointer to object else the object will be revoked by system even you have tones of weak pointers to the object


keepRocking

Avoid Strong Reference Cycles when Capturing self

Blocks in objective C are really awesome...but...

If you need to capture self in a block, such as when defining a callback block, it’s important to consider the memory management implications.

Blocks maintain strong references to any captured objects, including self, which means that it’s easy to end up with a strong reference cycle if, for example, an object maintains a copy property for a block that captures self:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
@interface TechClass : NSObject
@property (copy) void (^block)(void);
@end

@implementation TechClass
- (void)configureBlock {
    self.block = ^{
        [self doWork];    // capturing a strong reference to self
                               // creates a strong reference cycle
    };
}
@end

To avoid this retain cycle we have to do changes as below 


1
2
3
4
5
6
7
- (void)configureBlock {
    TechClass * __weak weakSelf = self;
    self.block = ^{
        [weakSelf doWork];   // capture the weak reference
                                  // to avoid the reference cycle
    }
}

This change makes sure that retain cycle is not created for self.
You can check all these scenario in sample code @ Sample Code

Writing String manipulation function for 'C' to understand (readonly/readwrite) string literals

We saw how char * and char [] are differently stored in memory in previous post
Now lets try to write simple string manipulation function. I will not write complex code as such this code will be more for writing safe functions which will do simple functionality without breaking the code.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include<stdio.h>
#include<string.h>
char* trim(char *string){
    
    int len = strlen(string);
    
    for(int i=0;i<len;i++){
        
        if(string[i]==' '){
            string[i]='*';
        }
    }
    return string;
}

int main(){
    
    char * string ="hello there";
    printf("%s",trim(string));
    return 0;
    
}

Can you guess what will be output ??
Its is 'Bus error: 10' (Read here & here on this)
wondering how! If you have understood are-char-str-char-str-same.html? then answer to this question is simple. string variable is stored in read-only memory.
If we change '* string' to 'string[]' like shown below

1
2
3
4
5
6
7
int main(){

char string[] ="hello there";
printf("%s",trim(string));
return 0;

}
Above code will behave as expected and will give output
'hello*there'
So what if you want to write such string manipulation functions of you own but if user of this function provide string literal from readonly memory you can not change that. what can be good way to achieve what we want without modifying readonly memory.
Lets modify some code in trim() function like below

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
char* trim(char *string){

  int len = strlen(string);
  char * iString  = (char*)calloc(len*sizeof(char)+1,0);

 iString[len]='\0';
 for(int i=0;i<len;i++){

   if(string[i]==' '){
    iString[i]='*';
   }else{
    iString[i]=string[i];
   }
 }
 return iString;
}

Now this method will be capable of handling char* / char[] input string with ease.
Note : User of trim() function should be responsible for free() ing memory (allocated to iString).

Are char * str & char str[] same ?

Lets have look at one of the bothering subject of 'C' to newbie programmers. Yes , You guessed it right it is POINTERS. nightmare of Computer science students.
(Here is interesting(for me at least ) discussion on Pointer's evilness)


First lets see basic definition of pointer -

pointer is a variable which contains the address in memory of another variable

Let's visualise memory location and pointer as above. You can see MemAd007 is valid memory location having some data value. Now there is another memory location labeled as pointer and having value as MemAd007 .
What is difference between pointer & MemAd007 memory location ?
Answer is pointer contain memory address and other data( its can be int, float...any data)
Lets consider sample code in C


1
2
3
4
5
6
7
8
#include<stdio.h>

int main(){

   char * str ="hello";
   char  s[10]="hi" ;
   return 0;
}

Now time for making hands dirty with assembly code ....
You can get assembly code from c using
#>gcc -O2 -S -c <program_name>
But instead I found website where we can get more informative assembly code from C.
Below is assembly code for above program. (You can use this tool to do it online - http://assembly.ynh.io/)


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
              .Ltext0:
               .section .rodata
              .LC0:
0000 68656C6C   .string "hello"
     6F00
               .text
               .globl main
              main:
              .LFB0:
               .cfi_startproc
0000 55         pushq %rbp
               .cfi_def_cfa_offset 16
               .cfi_offset 6, -16
0001 4889E5     movq %rsp, %rbp
               .cfi_def_cfa_register 6
0004 4883EC30   subq $48, %rsp
0008 64488B04   movq %fs:40, %rax
     25280000 
     00
0011 488945F8   movq %rax, -8(%rbp)
0015 31C0       xorl %eax, %eax
0017 48C745D8   movq $.LC0, -40(%rbp)
     00000000 
001f 48C745E0   movq $26984, -32(%rbp)
     68690000 
0027 66C745E8   movw $0, -24(%rbp)
     0000
002d B8000000   movl $0, %eax
     00
0032 488B55F8   movq -8(%rbp), %rdx
0036 64483314   xorq %fs:40, %rdx
     25280000 
     00
003f 7405       je .L3
0041 E8000000   call __stack_chk_fail
     00
              .L3:
0046 C9         leave
               .cfi_def_cfa 7, 8
0047 C3         ret
               .cfi_endproc
              .LFE0:
              .Letext0:

You can see here there is section called .rodata which stores value "hello" as it is. You can read more about this data section @ http://www.bravegnu.org/gnu-eprog/c-startup.html.
So its clear that s, and str are stored differently in memory itself. As "hello" stored in .rodata section, which is read only section hence we can not modify contents of 'str' but we can modify contents of 's' easily.
Hope this small experiment clears you doubt.