Posts from the “iOS” Category

Highlights of Dynamic Constraints

Dynamic constraints could be efficient and powerful if we get it work correctly. In other words, we need to make sure:

  • Do the deactivation/activation of constraints at the right place.
  • Try to avoid frequent view hierarchy changes (addSubview, removeFromSuperview).
  • Make sure active constraints don’t have conflicts.

Let’s dive into details of the three aspects:

Do the deactivation/activation of constraints at the right place:

For a view, `updateConstraints` is where the system gets the constraints for subviews and is efficient to apply constraint changes. To trigger `updateConstraints`, call `setNeedsUpdateConstraints` wherever the constraints need to be changed.

Try to avoid frequent view hierarchy changes (addSubview, removeFromSuperview):

Frequent view hierarchy changes requires recalculation of the layout, which is not efficient for displaying the views, and could cause update of the view not visually smooth.

Make sure active constraints don’t conflict:

Although iOS automatically deactivating conflicted constraints based on some magic in the system, it’s better to not contain conflicted constraints in the first place. Because older iOS versions may not be as intelligent as the newer ones dealing with constraints conflicts, and it could results in unexpected layout.

Weakify Self

Note: weakifying self in a block has a few reasons.

If the block is retained by self, weakifying self helps avoiding retain cycle.

Otherwise, if the block is not retained by self, WE STILL WANNA WEAKIFY SELF because we don’t wanna anything unknown to retain self especially when self is complicated (i.e. view controller). Retaining self by in a block may ultimately delay the release of the instance of type to which self belongs.

Conclusion is, always weakify self in blocks. But remembering the reasons is important to avoid not weakifying when some reasons are forgotten.

Convert NSData to NSString

NSData -> NSString:

Ignore stringWithUTF8String and use initWithData:encoding:NSUTFStringEncoding because stringWithUTF8String expects a NUL terminated buffer whereas NSData doesn’t guarantee that. Invalid NSData could cause a nil result using stringWithUTF8String.

NSDate Formatting Convenience

Go to the “NSDateFormatter” to preview the result of your format:

And refer to the following table to construct the format:

iPhone NSDateFormatter date formatting table