What's wrong with this block formating code? - objective-c

-(void) vPerformBlockOnAllAutoCompleteHandler:((^)(BGMotherofAutoCompleteHandler * acHandler))block
{
for (BGMotherofAutoCompleteHandler * acHandler in [self arBGKeywordAutoCompleteHandlers]) {
block(acHandler);
}
}
Okay, so block is a block that takes BGMotherofAutoCompleteHandler as argument. I went through the loop and call block(acHandler).
What's wrong?
The error is:
/business/Dropbox/badgers/BadgerNew/BGSearchController3.m:218:49: Expected a type. It seems to me I have to add void before the block.
So this works
-(void) vPerformBlockOnAllAutoCompleteHandler1:(void (^)(BGMotherofAutoCompleteHandler * acHandler))block
{
for (BGMotherofAutoCompleteHandler * acHandler in [self arBGKeywordAutoCompleteHandlers]) {
block(acHandler);
}
}
However I do not need to add that void if the block does not requires parameter. I found this very strange.

The syntax is:
- (void)vPerformBlockOnAllAutoCompleteHandler:(void(^)(BGMotherofAutoCompleteHandler*))block
{
for (BGMotherofAutoCompleteHandler * at in [self arBGKeywordAutoCompleteHandlers]) {
block(at);
}
}
Here's a cheat sheet.

Related

In Objective C, what happens if we pass nil or null to #synchronized() block?

Usually we will pass an object to #synchronized() block for unique reference. for example,
+(id)sharedDBHandler
{
#synchronized (self) {
if (sDBHandler == nil) {
sDBHandler = [self new];
}
}
return sDBHandler;
}
what happens if we pass nil to it?
It doesn't #synchronize() at all. No locks taken. No-op. Undefined behavior.
Perfectly valid question, btw, regardless of whether the code is antiquated and no longer the correct means of generating a singleton.
From the github repository. While not a documented claim, breaking this policy would cause compatibility hell.
int objc_sync_enter(id obj)
{
int result = OBJC_SYNC_SUCCESS;
if (obj) {
SyncData* data = id2data(obj, ACQUIRE);
assert(data);
data->mutex.lock();
} else {
// #synchronized(nil) does nothing
if (DebugNilSync) {
_objc_inform("NIL SYNC DEBUG: #synchronized(nil); set a breakpoint on objc_sync_nil to debug");
}
objc_sync_nil();
}
return result;
}
Where:
BREAKPOINT_FUNCTION(
void objc_sync_nil(void)
);

Using a function in NSSetUncaughtExceptionHandler

I want to reference some state in a NSSetUncaughtExceptionHandler, and so don't want to pass in a function but a method instead. But how?? The state I need to reference is a callback from a react native app. So far i have:
#import "RNUncaughtExceptionReporter.h"
#implementation RNUncaughtExceptionReporter
- (dispatch_queue_t)methodQueue
{
return dispatch_get_main_queue();
}
RCT_EXPORT_MODULE()
RCT_EXPORT_METHOD(listen:(RCTResponseSenderBlock)listener)
{
callback = listener;
NSSetUncaughtExceptionHandler(/* what goes here? */);
}
- (void) unhandledExceptionHandler(NSException *exception) {
callback(#[#"something went wrong..."]);// todo: send the detail of the exception
}
#end
try this !
NSSetUncaughtExceptionHandler (&UncaughtExceptionHandler);
void UncaughtExceptionHandler(NSException* exception)
{
/* do anything u want with the exception */
}

Converting objective-c block to Swift closure

I am trying to convert this Objective-C block into Swift:
[self.client downloadEntity:#"Students" withParams: nil success:^(id response) {
// execute code
}
failure:^(NSError *error) {
// Execute code
}];
This is my code in Swift, but the syntax seems to be a bit off:
client.downloadEntity("Students", withParams: nil, success: {(students: [AnyObject]!) -> Void in
print("here")
}, failure: { (error: NSError!) -> Void! in
print ("here")
}
This is giving me a few compilation errors:
Value of 'AnyObject' has no member 'downloadEntity'
It is complaining about the lack of commas (,) right after the failure part of the code
Try this:
client.downloadEntity("Student", withParams: nil,
success: { (responseObj) -> Void in
print("success: \(responseObj)")
},
failure: { (errorObj) -> Void in
print("treat here (in this block) the error! error:\(errorObj)")
})
You need to switch to the new Swift error syntax, and you can also using trailing closures. I had to use a bool for the example to show how you would call your success closure, or you would throw an error.
var wasSuccessful = true // This is just here so this compiles and runs
// This is a custom error type. If you are using something that throws an
// NSError, you don't need this.
enum Error:ErrorType {
case DownloadFailed
}
// Hopefully you have control over this method and you can update
// the signature and body to something similar to this:
func downloadEntity(entityName: String, success: ([AnyObject]) -> Void) throws {
let students = [AnyObject]()
// download your entity
if wasSuccessful {
// Call your success completion handler
success(students)
}
else {
throw Error.DownloadFailed
}
}
When you have a function that can throw an error, you need to call it with try inside a do/catch block.
// Calling a function that can throw
do {
try downloadEntity("Students") { students in
print("Download Succeded")
}
}
catch Error.DownloadFailed {
print("Download Failed")
}
// If you are handling NSError use this block instead of the one above
// catch let error as NSError {
// print(error.description)
// }

How to add a completion block to an IOS call

I need to wait for savePhototoImage to complete before moving on in my processing. I assume a completion block is the way to do this.
I have seen a few completion blocks in IOS code, but do not know much about how they are made up.
Can a completion block be added to any function and if so, what would be the correct syntax to add one to this function?
BOOL saved = [Network savePhotoImage:img :self.description :#"Photo"];
ViewController.m
[Network savePhotoImage:img :self.description :#"Photo" withCallback:^(BOOL success)
{
NSLog(#"executing callback");
if (success)
{
NSLog(#"got callback success");
}
else
{
NSLog(#"got callback failure");
}
}];
Network.m
+ (void)savePhotoImage:(UIImage*)PhotoImage :(NSString*)description :(NSString*)imageName withCallback:(ASCompletionBlock)callback
{
add workdone code here...
if (workdone)
callback(YES);
} else {
callback(NO);
}
}
Network.h
typedef void (^ASCompletionBlock)(BOOL success);
+ (void)savePhotoImage:(UIImage*)PhotoImage :(NSString*)description : (NSString*)imageName withCallback:(ASCompletionBlock)callback;

Obj-C function declaration needs semi-colon?

This is really simple but driving me nuts.
I am trying to implement a simple function in my Objective-C code. When I write this,
NSInteger Sort_Function(id id1, id id2, void *context) {
}
I get an error that a semi-colon was expected at the end of the declaration. However, I've seen this type of syntax in many, many examples. What could I possibly be doing wrong? If it matters, this is an iOS app and the function is nested in an if clause. Thanks in advance.
The function definition -- this snippet you posted -- is "nested in a if clause"? That's unfortunately illegal in C (and Obj-C by extension) -- all function declarations and definitions have to be at the top level of the file. Inside an #implementation section is also an option:
// Start of file
// Declaration or definition valid here
void my_func(void); // Declaration
void my_other_func(void);
void my_third_func(void);
void my_func(void) { // Definition
return;
}
#implementation MyClass
// Definition also valid here
void my_other_func(void) {
return;
}
- (void) myMethod {
if( YES ){
void my_third_func(void) { // Invalid here
return;
}
}
}
#end
Is it possible you're confusing the function syntax with block syntax?
// The caret indicates definition of a block, sort of an anonymous function
int (^myBlock)(int);
myBlock = ^int (int my_int) {
return my_int;
};