Fix race conditions in RTCPeerConnectionFactoryTests

testSetCodecPreferences and testSetHeaderExtensionsToNegotiate call
offerForConstraints:completionHandler:, which asynchronously dispatches
CreateOffer to the signaling thread. Both tests previously executed
[peerConnection close] and object deallocation before waiting on
dispatch_semaphore_wait. Closing and deallocating peerConnection
destroys the session, invalidating weak pointers on the signaling thread
and causing the asynchronous CreateOffer task to fail. This change
defers closure and deallocation until after the semaphore wait
completes.

Bug: none
Change-Id: If269ceb4918fa0fcc4189044f35e6c1e72a6b6cc
Reviewed-on: https://webrtc-review.googlesource.com/c/src/+/472661
Commit-Queue: Artem Titov <titovartem@webrtc.org>
Reviewed-by: Artem Titov <titovartem@webrtc.org>
Auto-Submit: Tomas Gunnarsson <tommi@webrtc.org>
Cr-Commit-Position: refs/heads/main@{#47714}
diff --git a/sdk/objc/unittests/RTCPeerConnectionFactory_xctest.m b/sdk/objc/unittests/RTCPeerConnectionFactory_xctest.m
index ec88d6d..5c5d7c7 100644
--- a/sdk/objc/unittests/RTCPeerConnectionFactory_xctest.m
+++ b/sdk/objc/unittests/RTCPeerConnectionFactory_xctest.m
@@ -543,14 +543,14 @@
               dispatch_semaphore_signal(semaphore);
             }];
 
+      dispatch_semaphore_wait(
+          semaphore, dispatch_time(DISPATCH_TIME_NOW, 15.0 * NSEC_PER_SEC));
+      XCTAssertTrue(completed);
+
       [peerConnection close];
       peerConnection = nil;
       factory = nil;
       tranceiver = nil;
-
-      dispatch_semaphore_wait(
-          semaphore, dispatch_time(DISPATCH_TIME_NOW, 15.0 * NSEC_PER_SEC));
-      XCTAssertTrue(completed);
     }
   }
 }
@@ -632,14 +632,14 @@
               dispatch_semaphore_signal(semaphore);
             }];
 
+      dispatch_semaphore_wait(
+          semaphore, dispatch_time(DISPATCH_TIME_NOW, 15.0 * NSEC_PER_SEC));
+      XCTAssertTrue(completed);
+
       [peerConnection close];
       peerConnection = nil;
       factory = nil;
       tranceiver = nil;
-
-      dispatch_semaphore_wait(
-          semaphore, dispatch_time(DISPATCH_TIME_NOW, 15.0 * NSEC_PER_SEC));
-      XCTAssertTrue(completed);
     }
   }
 }