Monthly Archives: May 2015

Using UIRefreshControl in UIScrollView

How to add refresh control to a scroll view

First, set your uiviewcontroller self.view background to black.

Then create a scroll view container and set it to red.

Then have the scroll view container add a refresh control.

Finally, draw an orange square and have the container add that.

self.view
—container
——-refresh control (operates on container as background)
——-square (other UIViews added to container will be pulled down)

Once you run the app and pull down, you’ll see that the refresh control is added onto the scroll view and operates using the scrollview as the background.

refresh_control_added

Code

NSInternalInconsistencyException

If you happen to try to add the refresh control to a uiviewcontroller’s self.view, you’ll get a compiler error:

NSInternalInconsistencyException’, reason: ‘UIRefreshControl may only be managed by a UITableViewController’

You can only add it to a UITable, UICollection, and UIScrollView.

Making a successful View transition when UIRefresh is pulled

If you want to transition your view beautifully when the user pulls down on the refresh control, set your controls up so that there are 2 containers.

container1 – refresh control, other views
container2 – refresh control, other views

Then when a refresh control is pulled, you hit the event method of the ‘pull’ and make sure you animate the containers to switch. Something like this:

Installing Tomcat on Mac

References:

http://blog.bobbyallen.me/2012/07/30/installing-tomcat-7-on-macosx/
http://www.marbelladev.com/tomcat-7-installation-in-osx-mountain-lion/
http://neutronote.com/?p=233

find out version of java you have

If you don’t have java you need to download the latest version. Go to java for instructions.

Download apache tomcat’s tar gz binary file and unzip it in your Downloads folder.

Extract the downloaded binary distribution onto ~/Download/apache-tomcat-7.0.30 .

Create directory in /usr/local if we don’t have it yet.

4.- To make it easy to replace this release with future releases, we are going to create a

symbolic link that we are going to use when referring to Tomcat:

5.- Change ownership of the /Libaray/Tomcat folder hierarchy:

Make all scripts executable:

put this in tomcat-users.xml:

copy and paste text into your bash_profile:

start your server:

stop your server:

Thread Safety in ios

ref – http://quellish.tumblr.com/post/101831085987/implementing-thread-safety-in-cocoa-ios

You have just introduced “threads” to your application, because doing everything on the same thread as the UI was starting to noticeably bog things down. At some point you have run into strange crashes or exceptions. Your application no longer behaves as it used to.

One problem you have likely introduced is sharing data between threads. If two threads can be changing something, you’re asking for trouble. The common solution to this problem is to protect access to that resource: to introduce some form of locking on the resource to only allow one thing to touch it at a time.

In Objective-C there are a number of ways to deal with this, with the most common being use of the @synchronized keyword to protect access to a block of code.
The @synchronized keyword

In Objective-C the @synchronized keyword provides an implicit reentrant lock on a unique identifier for a block of code. For example:

This prevents the code inside that statement from executing until any contention on foo is released. This prevents more than one thread from using that lock at a time.

Because the lock is implicit, there is overhead even when the lock is not in contention. If nothing else is accessing the lock, the system still has to find the lock, which takes time. The lock used is recursive, which is more expensive than a non-recursive lock. Additionally, the @syncrhonized keyword does put into place an exception handler that adds some additional overhead. Because @synchronized uses a lock, it’s possible to use it in ways that result in a deadlock.

@synchronized is a blunt instrument, and unfortunately is often used to hammer away “threading problems”.

Lock-free synchronization

The point of synchronizing access to something is to ensure only one thing can access it at a time. On MacOS and iOS we have the concept of queues for concurrency. A serial queue is an ideal way to protect access without the potential costs of locking. If every access to the protected resource occurs through a serial queue the problem is solved – the queue guarantees that only one thing will be accessing it at a time. For example:

Because the serial queue executes work in FIFO order and only one block at a time, the statement is protected. Unlike using a lock, this can’t deadlock.

This is the preferred method for protecting a resource shared between threads on MacOS and iOS.
Not needing synchronization at all

The recommended solution for this problem is not to have it all. If you are sharing a mutable resource between threads, question why.

You may have noticed that much of Foundation is class clusters that provide both immutable (i.e. NSString) and immutable (i.e. NSMutableString) versions of a given class cluster object. An immutable object cannot be changed after it is created – it has a finite, determinate state and life cycle. Because of this, immutable objects are safe to exchange betweeen threads – there is no problem with two threads changing the object at the same time. Mutable objects should be considered unsafe unless they are specifically documented to be safe to access across threads.

Unfortunately few objective-c developers follow this practice even though it is one of the SOLID object oriented design principles. The developer will run into a mysterious crash or exception, google it, and after reading a few Stack Overflow articles start stamping @synchronized all over the place.
In practice

Implementing a reader-writer lock or the equivalent in objective-c is easy, and easy to get wrong. You will commonly see something like this:

Which isn’t effective for several reasons. Each method is synchronizing on self, so ANY access to self or it’s members will cause a contention.

By overriding the accessor methods for the foo property and accessing the instance variables directly the application may not be correctly managing the memory associated with foo.

A better implementation would be:

This uses a private property to ensure correct memory management. Note that because it’s of type id, we retain it strongly. If foo were a type that is a class cluster, we would prefer declaring it as copy rather than strong. That would ensure that even if it were set with a mutable object, the accessor would make an immutable copy before setting it. Instead of using @synchronized to provide an implicit lock, we’re using a serial queue to protect access to the private property. Note that in the case where we return the value in the getter we use dispatch_sync to make the calling thread wait for the result. This does use a lock, but the lock does not have most of the disadvantages of @synchronized and is only used in the reading case. An alternative would be to pass a block to be executed when the value is available:

This not only removes the need to block, but executes asynchronously.

Yono – Period Tracking

Updating of the calendar’s view for given Changing Status

The MeStatusViewController needs to communicate with CalendarViewController whenever a user has changed status. We do this by notifications because we are communicating ViewController to ViewController in a MVC setting.

MeStatusViewController

Once an update is notified by MeStatusViewController, we call CalendarViewcontroller’s updateCalendarView using previously saved period history.

CalendarViewcontroller

When we update the calendar, notice we get the status of the app. Hence we’ll either get “Period Tracking” or “Trying to Conceive”. We process the period dates according to either these status.

CalendarViewcontroller

iCarousel dates

The dates on the iCarousel, is calculated this way:

component setDay to -365 and then uses dateByAddingComponents:toDate: will generate a NSDate 365 days prior to today.
For example, if today is 5/22/15, then the result would be 5/22/14
-364 5/23/14
-363 5/24/14
…all the way until we have one full year of nsdates from 5/23/14 to 5/22/15.
As each date is generated, we insert it into daysCarouselDictionary.

daysCarouselDictionary is used in iCarousel delegate methods for data display.

We generate 2 years of dates, where today is smack in the middle.
Hence continuing from previous example, we then generate a future year
1 5/24/15
2 5/25/15
….
365 5/22/16

Thus, that is how we fill the iCarousel with those perspective dates.

Coloring of the period dates

CalendarViewController.m

Yono – Logging out

Logout – back to default status

Basically when we log out, 2 basic things happen.

1) We are at the settings view controller where we create/log in…etc. We that settings controller so that we’re back to the main tabs view controller.m

2) we empty period dates in our calendar. That way all the period flows the user entered have been removed so that we start fresh for guest.

3) we need to clean the probabilities, then refresh it so that the calendar has no probability.

MainTabsViewController.m –

Thread Basics (Instantiations)

SomeClass header

SomeClass implementation

main

log output:

Thread B processing on object 0x7fe839416a70 ‘s method, member variable address: 0x7fe839416a78, number just changed to 0
Thread B processing on object 0x7fe839416a70 ‘s method, member variable address: 0x7fe839416a78, number just changed to 1
Thread A processing on object 0x7fe83960e340 ‘s method, member variable address: 0x7fe83960e348, number just changed to 0
Thread A processing on object 0x7fe83960e340 ‘s method, member variable address: 0x7fe83960e348, number just changed to 1
Thread B processing on object 0x7fe839416a70 ‘s method, member variable address: 0x7fe839416a78, number just changed to 2
Thread B processing on object 0x7fe839416a70 ‘s method, member variable address: 0x7fe839416a78, number just changed to 3
Thread A processing on object 0x7fe83960e340 ‘s method, member variable address: 0x7fe83960e348, number just changed to 2

As you can see

Thread A processes on object 0x7fe83960e340
Thread B processes on object 0x7fe839416a70

The access different member variables, in particular

Thread A processes on object 0x7fe83960e340’s member variable 0x7fe83960e348
Thread B processes on object 0x7fe839416a70’s member variable 0x7fe839416a78

Both threads do their work on their own respective objects because those objects were allocated on the thread’s own stack in main’s

Threads Basics (static, class methods, and singletons)

Class methods are shared by threads

All methods who run a class method on a class name are using the same class and running through that one method. That class method acts as an entry point. You do this by looking at the address of self.

If you run couple of threads through this classMethod, you should something like this:

classMethod – thread B, self address is: 0x107159380
classMethod – thread A, self address is: 0x107159380
classMethod – thread C, self address is: 0x107159380

They all have the same address for ‘self’. Which means there exist only one blueprint of the class in which these class methods belong to.

static variables are shared by threads

you’ll see that in the output, they all display the static variable’s address, which is the same for all threads:

classMethod – thread B, local static int number’s address is: 0x1071594e8
classMethod – thread C, local static int number’s address is: 0x1071594e8
classMethod – thread A, local static int number’s address is: 0x1071594e8

local variables are not shared. They belong to their own thread stack

you’ll see from output the the addresses of the local variable is different, which tells us that each thread have their own local variables:

classMethod – thread D, local int number’s address is: 0x11420fc44
classMethod – thread B, local int number’s address is: 0x114109c44
classMethod – thread C, local int number’s address is: 0x11418cc44
classMethod – thread F, local int number’s address is: 0x114315c44
classMethod – thread E, local int number’s address is: 0x114292c44

non-static variables are not allowed

If we were to declare an int number in our class:

and you try to use it in your static method, you’d get an error. Because only static variables are used in static methods. Its not intuitive or possible for a class method to keep track of instantiated variables. It simply does not work this way.

the variable ‘number’ is connected to an instantiation (object) of SomeClass.

No static class variables

You cannot declare ‘number’ in our previous example to be static because in objective c, there are no class static variables.

However, you CAN declare a static variable globally and use it in SomeClass’s static method. That is the basis of how a lot of singletons are made.

Example Singleton

.h

.m

As you notice we don’t let others copy or allocate our singleton by returning self. ….because there can be only 1 singleton.

Full Example

SomeClass header

SomeClass implementation

main – appdelegate

Result

classMethod2 – thread D, self address is: 0x107159380
classMethod – thread B, self address is: 0x107159380
classMethod – thread A, self address is: 0x107159380
classMethod – thread C, self address is: 0x107159380
classMethod2 – thread E, self address is: 0x107159380
classMethod2 – thread F, self address is: 0x107159380
classMethod2 – thread D, local static int number’s address is: 0x1071594ec
classMethod – thread B, local static int number’s address is: 0x1071594e8
classMethod – thread C, local static int number’s address is: 0x1071594e8
classMethod – thread A, local static int number’s address is: 0x1071594e8
classMethod2 – thread F, local static int number’s address is: 0x1071594ec
classMethod2 – thread E, local static int number’s address is: 0x1071594ec
classMethod – thread A, local int number’s address is: 0x114086c44
classMethod2 – thread D, local int number’s address is: 0x11420fc44
classMethod – thread B, local int number’s address is: 0x114109c44
classMethod – thread C, local int number’s address is: 0x11418cc44
classMethod2 – thread F, local int number’s address is: 0x114315c44
classMethod2 – thread E, local int number’s address is: 0x114292c44

Flow Dates ( period dates )

Taking in flow dates and updating your Calendar

The app starts and the user presses on the flow dates button on the top right.
User enters 2 different flow dates and clicks on “Save History” on the top left.

PeriodHistoryViewController’s “Save History” is a back button. Its responder is:

After the user selects the average cycle length we hit:

Then it goes to MainTabsViewController’s

Then, CalendarViewController’s

Factory Methods in Objective C and iOS

ref – http://stackoverflow.com/questions/19450940/what-is-the-purpose-of-using-a-factory-method-in-objective-c-context

Objective-C does not have constructor methods that are available in other programming languages. Factory methods are essentially Objective C’s constructor methods. They allow you to allocate memory for your object and initialize the values.

In your class, add methods with this pattern:

Then in main, you can do:

It saves you from having to do this:

Furthermore

A factory method can be any class or instance method which returns a newly created and initialized object.

A “class factory method” in a more strict Objective-C context is any class method of a class Class whose name begins with class.., with its prefix stripped and first letter lowercased. Example for class Foo:

One reason to use class factory methods is for convenience. If you have a class Foo it may be created as follows in the usual way:

A convenient class factory method may now be used as this:

However, there are other reasons where a class factory method is useful:

Suppose for example that the initWithParam: method can fail. Then there is much confusion about how this should be handled: should one throw an exception within init? Or should one return nil? There is controversy debate about the right approach in the community. Both approaches have subtle issues, including memory leaks which can not be avoided.

Thus, the most reasonable approach in such a case would be to use a class factory method with an error parameter. Here, you would get a Foo object as follows:

Now, the rule is: If foo is nil, there was an error, and one can obtain detailed info about the error with the output parameter error:

Typically, the implementation would look as below:

Another reason is to implement “class clusters”. That basically means that a class factory method returns a subclass of the class. An example is the NSStream class.

The NSInputStream class has a class factory method:

This returns a specialized class of NSInputStream.

In the pre-era of ARC there is an important detail:

Objects returned from a class factory method are ‘autoreleased’. In other words, the client receiving the object does not own it – and thus does not need to release it.

Nowadays, with ARC these details became blurred: you do not need to release those objects manually anyway. How and when the object gets actually released is also subject to compiler optimizations.

static in objective c vs java

ref –
http://stackoverflow.com/questions/4965048/static-variables-in-objective-c-what-do-they-do
http://stackoverflow.com/questions/2649213/in-laymans-terms-what-does-static-mean-in-java

OBJECTIVE C STATIC VARIABLES

In both C and Objective-C, a static variable is a variable that is allocated for the entire lifetime of a program.

This is in contrast to automatic variables

  • whose lifetime exists during a single function call
  • and dynamically-allocated variables like objects, which can be released from memory when no longer used
  • More simply put, a static variable’s value is maintained throughout all function/method calls.

    On the other hand

    Say you have this:

    Every call to f() will return the value 15.

    static variable to mimic class variables

    In the context of Objective-C classes, static variables are often used to mimic class variables, as Objective-C does not have class variables (other languages, such as Java, do). For instance, say you want to lazily initialize an object, and only return that object. You might see this:

    obj will be initialized the first time classObject is called; subsequent invocations of classObject will return the same object. You could check this by logging the address of the object:

    NSLog(@”obj is at %p”, [MyObject sharedObject]);
    NSLog(@”obj is at %p”, [MyObject sharedObject]); // Will print the same address both times

    Furthermore, obj will be visible to all methods in MyObject.

    This technique is used to implemented singleton classes in Objective-C as well.

    Static Variables in Java

    static means that the variable or method marked as such is available at the class level. In other words, you don’t need to create an instance of the class to access it.

    So, instead of creating an instance of Foo and then calling doStuff like this:

    You just call the method directly against the class, like so:

    There’s just one of it because it belongs to the class.
    Thus, it should be mentioned that a static field is shared by all instances of the class, thus all see the same value of it.